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.
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
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.