avatarCaleb

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

676

Abstract

d-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div><figure id="035f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*omfa0JwF4OwYcJplkfGsOQ.png"><figcaption></figcaption></figure><p id="f372">那你看看這三個媒體,不分政治取向,如何寫她?</p><figure id="3727"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ash4CSeuD85I2mKOUB9QgA.png"><figcaption></figcaption></figure><p id="e82a">對付,和對待,有什麼分別?</p><figure id="b429"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Z_gv519rWWdgbiEny-J80A.png"><figcaption></figcaption></figure><figure id="ce82"><img src="htt

Options

ps://cdn-images-1.readmedium.com/v2/resize:fit:800/1*NwgG-JjszBSrypqL7-cszA.png"><figcaption></figcaption></figure><figure id="32a2"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*_Y4aK9Q0X2zM7QVprX-_gg.png"><figcaption></figcaption></figure><p id="5158"><b>你為什麼這樣對待我?</b></p><p id="55cc"><b>你為什麼這樣對付我?</b></p><p id="e5cf">用小學中文的程度都知道有分野,為何會變成這樣的呢?</p><p id="ff8a">是新聞公報,以及在網路的短片,電台的聲帶都出錯,經過AI修正,所以777這種好打得,就會說「對付我」這種<b>「大婆受委屈家陣你要幫我」</b>的字眼?</p><p id="17a0">對待我,我覺得都有點敵意,但都尚算中性。至少不會說「外國勢力在對付」她那麼「撩交嗌」。</p><p id="affa">還是,大家都知道,這個世界覺得把777罵到半死就有收視,所以就付待不分?而你寫出來,是不是就是幫了777了?常聽人說,什麼人很愛罵人是content farm……</p><p id="d383">那,這一次,究竟是付,還是待,有人在乎嗎?</p></article></body>

How You Can Create Your Own Real-Time Multiplayer Game with Node.js and Socket.IO

In the last decade, we have seen a rapid evolution in the gaming industry. Especially in multiplayer games, where players from different corners of the world can connect and compete against each other in real-time. This might sound like some high-tech wizardry out of your reach, but what if I told you that creating your own multiplayer game is simpler than you think?

If you have a basic knowledge of JavaScript and a passion for games, then you’re already halfway there!

The technologies we’ll be using are Node.js, a popular server-side JavaScript runtime, and Socket.IO, a real-time engine that allows for event-based communication between clients and servers.

Unsplash

Part 1: Setting Up Your Environment

Let’s roll up our sleeves and start our journey. The first step is setting up the environment.

We need Node.js and npm (Node package manager) installed on your machine.

You can download and install Node.js and npm from their official website. Node.js will be our foundation, the earth where our game universe will reside.

Create a new directory on your computer where you’ll store your game’s files and navigate to it in your terminal.

Initialize a new Node.js application by running npm init -y.

This will create a package.json file, the recipe book that Node.js uses to keep track of your app's packages and settings.

Next, we’ll install Express and Socket.IO by running npm install express socket.io.

Express will act as our courier, delivering client requests to our server, while Socket.IO is our teleportation device, letting players interact in real time.

Part 2: Building The Game Server

With the environment set up, let’s now create our game server.

Create a new file called server.js and start by requiring our packages and setting up a basic Express server:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

// Our Express app
const app = express();

// Our server
const server = http.createServer(app);

// Setup socket.io to use our server
const io = socketIO(server);

Now that our game server is ready, let’s add some logic to handle connections from players.

With Socket.IO, we can listen for certain events and respond to them accordingly:

io.on('connection', socket => {
  console.log('A player has connected');

  // Handle disconnection
  socket.on('disconnect', () => {
    console.log('A player has disconnected');
  });
});

Part 3: Handling Game Logic

The game logic depends on the type of game you are developing. This could be a racing game, a quiz, a chess game, etc.

For simplicity, let’s assume we’re building a simple trivia game.

When a player connects, we will send them a question. If they answer correctly, we will send them another question.

const questions = [
  { question: "What is 2 + 2?", answer: "4" },
  { question: "Capital of England?", answer: "London" },
  { question: 'Who wrote the book "1984"?', answer: "George Orwell" },
  {
    question:
      "What is the Answer to the Ultimate Question of Life, The Universe, and Everything?",
    answer: "42",
  },
  { question: "In which year was the first moon landing?", answer: "1969" },
  { question: "What is the square root of 144?", answer: "12" },
  // Add as many questions as you like...
];

io.on('connection', socket => {
  let questionIndex = 0;
  
  socket.emit('question', questions[questionIndex]);

  socket.on('answer', (answer) => {
    if (answer === questions[questionIndex].answer) {
      questionIndex++;
      socket.emit('correct');
      if (questionIndex < questions.length) {
        socket.emit('question', questions[questionIndex]);
      } else {
        socket.emit('end');
      }
    } else {
      socket.emit('incorrect');
    }
  });

  socket.on('disconnect', () => {
    console.log('A player has disconnected');
  });
});

Part 4: Connecting Clients

The final part of our game is the client side.

This can be an HTML page with a script that connects to our server and listens for the events we’re emitting.

Here’s a simple example using plain JavaScript. Create a new file called index.html:

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io.connect('http://localhost:3000');

  socket.on('question', (question) => {
    const answer = prompt(question.question);
    socket.emit('answer', answer);
  });

  socket.on('correct', () => {
    alert('Correct answer!');
  });

  socket.on('incorrect', () => {
    alert('Wrong answer. Try again!');
  });

  socket.on('end', () => {
    alert('Congratulations! You answered all questions correctly.');
  });
</script>

Part 5: Testing Your Game

It’s crucial to test your game to ensure it’s working as expected. Let’s see how we can do it.

First, we need to make sure our server is running and listening for incoming connections.

At the end of our server.js file, add the following lines of code:

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

Here, we’re telling our server to listen for connections on a port, either a port defined in our environment variables (useful when deploying to platforms) or port 3000 if no environment variable is found.

In your server.js file, add the following code before the server starts listening. This will serve your index.html file when you access your server's root URL:

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

Your file should look like this:

const express = require("express");
const http = require("http");
const socketIO = require("socket.io");

// Our Express app
const app = express();

// Our server
const server = http.createServer(app);

// Setup socket.io to use our server
const io = socketIO(server);

const questions = [
  { question: "What is 2 + 2?", answer: "4" },
  { question: "Capital of England?", answer: "London" },
  { question: 'Who wrote the book "1984"?', answer: "George Orwell" },
  {
    question:
      "What is the Answer to the Ultimate Question of Life, The Universe, and Everything?",
    answer: "42",
  },
  { question: "In which year was the first moon landing?", answer: "1969" },
  { question: "What is the square root of 144?", answer: "12" },
  // Add as many questions as you like...
];

io.on("connection", (socket) => {
  let questionIndex = 0;

  socket.emit("question", questions[questionIndex]);

  socket.on("answer", (answer) => {
    if (answer === questions[questionIndex].answer) {
      questionIndex++;
      socket.emit("correct");
      if (questionIndex < questions.length) {
        socket.emit("question", questions[questionIndex]);
      } else {
        socket.emit("end");
      }
    } else {
      socket.emit("incorrect");
    }
  });

  socket.on("disconnect", () => {
    console.log("A player has disconnected");
  });
});

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

You can start your server by running the command node server.js in your terminal. You should see a message saying "Server is running on port 3000".

Now, you can open your web browser and go to http://localhost:3000. If everything is set up correctly, you should be prompted with the first question of your trivia game.

Remember to restart your server every time you make a change to your server.js file.

Since Node.js version 18.11.0, the Node.js team has introduced a built-in feature that allows you to restart the application automatically when file changes in the directory are detected, which eliminates the need for nodemon in many cases. This feature can be used with the --watch flag.

So, in your package.json, define a start script:

"scripts": {
  "start": "node --watch server.js"
}

Now, you can start your server with the command npm start in your terminal.

This will run the server.js file with Node.js, and it will automatically restart the server whenever it detects a change in server.js or any other file in the same directory.

Congratulations! You have created a basic real-time multiplayer game using Node.js and Socket.IO.

Socket.IO

Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between the browser (client) and the server.

It’s a powerful tool when building real-time applications such as multiplayer games, live chat systems, or apps that require instant data updates.

In the context of our multiplayer game tutorial, here are the main uses of Socket.IO:

  1. Real-time communication: The primary use of Socket.IO in our game is to enable real-time communication between the server and the connected clients. When a player joins the game, the server can instantly send them a question, and when the player submits their answer, the server can instantly check the answer and respond.
  2. Event-driven architecture: Socket.IO operates on an event-driven model. In our game, this means the server listens for specific events like ‘connection’, ‘disconnect’, or ‘answer’. Similarly, the client listens for events like ‘question’, ‘correct’, ‘incorrect’, and ‘end’. This event-driven approach fits perfectly with the dynamics of a multiplayer game where actions are usually triggered by user inputs or system events.
  3. Broadcaster: Socket.IO provides a feature to broadcast a message to all connected clients. In the context of a multiplayer game, it can be used to update all players about the state of the game, such as the scores of other players, or the announcement of the game winner.
  4. Multiplexing and rooms: In more complex multiplayer games, you can use Socket.IO’s support for multiplexing and rooms to manage separate channels of communication or organize the players into different game rooms.

In essence, Socket.IO makes our multiplayer game possible by allowing real-time, event-driven, and efficient communication between the server and the players. Without it, we would have to resort to slower, more resource-intensive methods like continuous polling, which wouldn’t provide the seamless and interactive experience we want in a multiplayer game.

Conclusion

In this tutorial, we just scratched the surface of what you can achieve with Node.js and Socket.IO. Our trivia game example is straightforward, but you can use these tools to create something as complex as a massive multiplayer online game.

The real fun begins when you start adding additional features to your game. Think about scoring systems, multiple rooms, chatting, or even integrating with databases to store player progress. The possibilities are endless!

Remember, in the realm of programming, perseverance is key. Keep coding, keep improving, and remember, the game is never over; it just gets to another level!

  1. Socket.IO Docs: The official Socket.IO documentation is a great resource. It provides a deep dive into various features and capabilities of Socket.IO.
  2. Express.js Guide: Get to know more about Express.js, how to create more complex server routes, use middleware, handle errors, and more.
  3. Node.js Course on Codecademy: This comprehensive course covers basic to advanced concepts of Node.js, which is useful to solidify your Node.js knowledge.
  4. Mozilla Developer Network (MDN) Web Docs: Mozilla offers excellent resources for learning about server-side development with Express and Node.js.
  5. Building a Real-Time Chat App with Socket.IO: Tutorialspoint provides this hands-on tutorial to create a real-time chat application using Socket.IO, a good practice after your multiplayer game.

Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:

If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.

[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. To know more about my creative process, read this article.]

In Plain English

Thank you for being a part of our community! Before you go:

Programming
JavaScript
Games
Socketio
Nodejs
Recommended from ReadMedium