开发者

Qt create game host

I have been creating a 2D game in Qt and I want to allow others to connect to hosted games to play. Would I just make a "server" in th开发者_StackOverflow中文版e game and allow others to connect to it?


If this is just a small project and you aren't intended to mass distribute it across the web (it doesn't sound like you are), then you can code up a simple socket server. You will need to modify your existing game code to send the "moves" as a message to the server. It will probably be easiest if you make up a simple network protocol to transmit the move data (if you are ambitious you could try serialization).

A pseudo-code example for a simple Tic-Tac-Toe game:

move1 = "Move X:1:1"  //placed an 'X' in square at row 1, column 1
move2 = "Move O:1:2"  //placed an 'O' in square at row 1, column 2

reset = "Reset"       //clear the board for a new game

...etc...

Your game code will need to generate these messages. Each player will run your game on their machine and this will act as the client.

Meanwhile, back in the server code, you will need to listen for move messages sent by the clients. When you get a move message, you need to broadcast the message to all the other clients so that there boards can be updated. I would recommend moving the server code outside of the game code for now; this will allow you to setup a dedicated server that will handle all the sockets and then everyone who wants to play will simply connect their client up to the server.

The basic idea is that your client needs to broadcast the details about what it's player is doing to the server, as well as listen for data from the server to update the details about the other player(s).

You can find some good discussion of high-level algorithms of a simple Client-Server game in this question as well: Algorithm for Client-Server Games

Hopefully this is enough to get you started! I have used this approach for some simple games (Tetris, Pong, etc) using C++/Qt and they worked out pretty well.

PS. Don't let the idea of writing your own server scare you off. It sounds daunting but it is really not very complicated at all (~100 lines of code or less) and a great learning experience.


Generally, one will need a few things to get something like that going.

Namely, a directory server. Maybe everyone connects to other players who host games to play, but you need to run a directory for games to be listed in order for people to connect.

Either that or you need to run a server and host them there. The choice is yours, the first option is probably easiest on you.


If I were you, I would make a server separated from, but bundled with, the "client". Believe me or not, many games out there take similar approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜