Share
Explore

s23 Assignment : NODE JS JavaScript: Build Your Very Own Ferengi Tanga Game

In Class Assignment Activity: s23 August 2:
Take this starter code which we did in Class:

Add the following functionalities:


Change the SCREEN background color to any random value for each Player Turn.
Add a BOM Field so user can also see the total number of bars of gold pressed Latinum that they have.

Put your Final Code into a GitHub Repository.
Make a TEXT file named as StudentName_StudentID.txt : e.g. PeanutBichon_C989393.txt
put your GITHUB URL into that text file.

Tonga is a strategic Ferengi game that is played with a combination of cards and roulette and which was played with two to eight players.

The object of the game is to win by acquiring as many bars of gold-pressed latinum as possible.

image.png

Welcome to the NODE JS JavaScript student lab learning workbook!

This guide will teach you the fundamentals of NODE JS and microservices, and how you can use them to create a networked Ferengi Tanga game.

Let's start our exciting journey!


Table of Contents

Introduction to NODE JS
Understanding Microservices
Game Designing: Ferengi Tanga Game
Building the Ferengi Tanga Game
Deploying the Game Using Microservices
Connecting Players Over Network

1. Introduction to NODE JS

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It's used for developing server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js allows you to run JavaScript on your server, outside a browser. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

2. Understanding Microservices

Microservices, or microservice architecture, is an architectural style that structures an application as a collection of small autonomous services, modeled around a business domain.
Microservices is an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities.
The microservice architecture enables the continuous delivery/deployment of large, complex applications and enables an organization to evolve its technology stack.


3. Game Designing: Ferengi Tanga Game

Ferengi Tanga is a simple and engaging card game. In our version, players will connect to the game server, join rooms, and play against each other.

4. Building the Ferengi Tanga Game

For building our Ferengi Tanga game, we'll use Node.js and Express.js for handling server-side operations. Socket.io will help us with real-time communication between the server and the client.

Setting up the Project

First, we need to install Node.js and initialize our project. Open your terminal and follow these steps:
// Install Node.js
npm install node

// Initialize your project
npm init

Building the Game Server

Next, we will create our game server. Let's start by installing Express.js and Socket.io:
// Install Express.js
npm install express

// Install Socket.io
npm install socket.io
Now, let's create our server:

// Load Express.js
const express = require('express');
const app = express();
const server = require('http').createServer(app);

// Load Socket.io
const io = require('socket.io')(server);

// Create a server on port 3000
server.listen(3000, function () {
console.log('Server listening on port 3000');
});
For the complete code of the game server, please refer to the detailed guide in this workbook.

5. Deploying the Game Using Microservices

Microservices will allow our game to scale and function efficiently. We will use Docker to containerize our game server and clients.

6. Connecting Players Over Network

With the help of Socket.io, we can create real-time, bi-directional communication between the server and the clients. This will allow players to play the game on network-connected computers.
This workbook will guide you through each of these steps in detail, with plenty of examples and exercises along the way. By the end of this workbook, you will have a working Ferengi Tanga game that players can enjoy over a network, powered by Node.js and microservices. Happy coding!

Ferengi Tanga game

Now, let's dive into the Ferengi Tanga game. It is a simple game where two players roll a die and the one with the higher score wins.

Server Setup

First, we will set up our Node.js server with Express:
javascriptCopy code
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('Welcome to the Ferengi Tanga Game!');
});

app.listen(port, () => {
console.log(`Ferengi Tanga Game server listening at http://localhost:${port}`);
});

You can run this script with the command node server.js (assuming you've saved it as server.js).

Game Logic

Now we'll write the game logic. We'll have a simple game where two players each roll a die, and the player with the higher roll wins:
const rollDie = () => Math.floor(Math.random() * 6) + 1;

app.get('/play', (req, res) => {
const player1Roll = rollDie();
const player2Roll = rollDie();

if (player1Roll > player2Roll) {
res.send(`Player 1 wins with a roll of ${player1Roll} against Player 2's roll of ${player2Roll}`);
} else if (player2Roll > player1Roll) {
res.send(`Player 2 wins with a roll of ${player2Roll} against Player 1's roll of ${player1Roll}`);
} else {
res.send(`It's a draw, both players rolled a ${player1Roll}`);
}
});

Microservices

The above code could be extended to a microservice architecture. For instance, you could have one service handling user registration and another service handling the game logic. For simplicity, we keep it in a monolithic design for this example.
Remember to install the necessary Node.js packages by running npm install express in your terminal before trying to run the server.
Please note that the code above is very simplistic, and a real-world application would have error handling, user sessions, a data store, etc.

Here is a very basic HTML client that interacts with your server. This example uses the fetch API to make GET requests to the /play endpoint on your server when the "Play" button is clicked, then displays the response in a paragraph.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ferengi Tanga Game</title>
</head>
<body>
<h1>Ferengi Tanga Game</h1>
<button id="play-button">Play</button>
<p id="game-result"></p>

<script>
document.getElementById('play-button').addEventListener('click', function() {
fetch('http://localhost:3000/play')
.then(response => response.text())
.then(data => {
document.getElementById('game-result').textContent = data;
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>

You can run this by saving it as index.html and opening it in a web browser. Remember that your server needs to be running, and it must be on the same port specified in the fetch URL.
Remember to replace 'http://localhost:3000/play' with your server URL if it's different.
Please note that you'll run into CORS (Cross-Origin Resource Sharing) issues if your server is not set up to handle requests from the origin of your HTML file. For this, you need to add CORS middleware to your server. You can do this by installing the CORS npm package with npm install cors and then adding it to your server:
javascriptCopy code
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(cors());

// ...the rest of your server code

This is a basic example and does not include user interfaces for player registration, score tracking, and other features that a complete game might have.

An updated version of the server and client where a user can bet bars of gold-pressed latinum on the game. The user starts with a certain amount of bars and then bets a number of bars each game.

Server Code:

First, let's install the necessary packages by running npm install express cors body-parser in your terminal.
javascriptCopy code
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(cors());
app.use(bodyParser.json());

let playerLatinum = 100; // The player starts with 100 bars of gold-pressed latinum

const rollDie = () => Math.floor(Math.random() * 6) + 1;

app.post('/play', (req, res) => {
const playerBet = req.body.bet;

if (playerBet > playerLatinum) {
res.json({
message: 'You do not have enough latinum for this bet!',
playerLatinum: playerLatinum
});
return;
}

const player1Roll = rollDie();
const player2Roll = rollDie();

if (player1Roll > player2Roll) {
playerLatinum += playerBet;
res.json({
message: `Player 1 wins with a roll of ${player1Roll} against Player 2's roll of ${player2Roll}. You won ${playerBet} bars of latinum!`,
playerLatinum: playerLatinum
});
} else if (player2Roll > player1Roll) {
playerLatinum -= playerBet;
res.json({
message: `Player 2 wins with a roll of ${player2Roll} against Player 1's roll of ${player1Roll}. You lost ${playerBet} bars of latinum!`,
playerLatinum: playerLatinum
});
} else {
res.json({
message: `It's a draw, both players rolled a ${player1Roll}`,
playerLatinum: playerLatinum
});
}
});

app.listen(port, () => {
console.log(`Ferengi Tanga Game server listening at http://localhost:${port}`);
});

HTML Client: game.html

// this is game.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ferengi Tanga Game</title>
</head>
<body>
<h1>Ferengi Tanga Game</h1>
<p id="latinum">You have 100 bars of gold-pressed latinum</p>
<input type="number" id="bet" min="1" value="1">
<button id="play-button">Play</button>
<p id="game-result"></p>

<script>
document.getElementById('play-button').addEventListener('click', function() {
const bet = document.getElementById('bet').value;
fetch('http://localhost:3000/play', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ bet: parseInt(bet) }),
})
.then(response => response.json())
.then(data => {
document.getElementById('game-result').textContent = data.message;
document.getElementById('latinum').textContent = 'You have ' + data.playerLatinum + ' bars of gold-pressed latinum';
})
.catch((error) => {
console.error('Error:', error);
});
});
</script>
</body>
</html>

Please note that when using $.ajax(), the URL is now set to '/play' instead of 'http://localhost:3000/play'. This is because '/play' is a relative path and it will automatically append to the current domain, which makes this code more flexible and reusable.

This file will be served when the user navigates to 'http://localhost:3000/game.html'. Remember to ensure the file is located in the directory being served by serve-static in your server code (in this case, a directory named 'public').
In this version, the user inputs the number of bars they want to bet in an input field. The client then sends this number to the server with a POST request when the "Play" button is clicked. The server checks if the user has enough bars to make the bet, updates the number of bars based on the game result, and sends the game result and the updated number of bars back to the client. The client then updates the displayed game result and number of bars.
Please note, this version still lacks proper user management, error handling, and user interface, among other features a complete game might have.

For the players' enjoyment and world building, provide a discussion of the ferengi currency of gold pressed latinum and the Rules of Acquision
Gold-Pressed Latinum
Gold-Pressed Latinum (GPL) is the primary currency in the Star Trek universe, particularly among the Ferengi. Latinum is a rare silver-colored liquid that cannot be replicated and thus holds its value. It's usually suspended within gold to produce GPL bars, slips, and strips. Here are the basic units:
Slip: The smallest denomination of GPL.
Strip: Equivalent to 100 slips.
Bar: Equivalent to 20 strips or 2,000 slips.
Brick: Equivalent to 20 bars, 400 strips, or 40,000 slips.
The use of GPL in trade and negotiation is a key part of Ferengi culture.
Ferengi Rules of Acquisition
The Ferengi Rules of Acquisition is a collection of 285 aphorisms, guidelines, and principles that are a sacred code of conduct for Ferengi commerce, written by the ultra-capitalistic race, the Ferengi. They cover all aspects of interaction with profit in mind.
While we don't have a list of all 285 rules, here are a few examples as seen in Star Trek:
"Once you have their money, never give it back."
"Never spend more for an acquisition than you have to."
"Keep your ears open and your eyes on the mark."
"Opportunity plus instinct equals profit."
"Greed is eternal."
These rules, although highly focused on profit, often provide humorous and insightful commentary on capitalist principles.
Keep in mind that this is all part of the fictional universe of Star Trek. In a real-world application, game developers might want to create their own unique currencies, cultures, and guidelines inspired by such fictional works.

Version 3 of the Game:


Improve the quality of this Web App game by folding in CSS and jQuery. Have the page color background change in response to game play such as winning latinum

Let's add some CSS for basic styling and use jQuery to help manage the user interactions.
Here's the updated HTML file:
htmlCopy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ferengi Tanga Game</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
transition: background-color 0.5s;
}
#play-button {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Ferengi Tanga Game</h1>
<p id="latinum">You have 100 bars of gold-pressed latinum</p>
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.