For the 10th week of the #JustCode Challenge I took a look at networking. For my project this time I’ve created a networked version of the Combat game, which has two tanks on the screen shooting at each other. The network version allows you to control one tank with the app running on your computer and someone else to control the other tank with the app running on their computer. I call it NetTank.
I made a version of Combat in Xojo a while ago (it’s included in the Xojo examples folder in the Download) so I figured I would start there. To provide network capabilities to a game, you generally want to go with something fast and that means UDP (User Datagram Protocol), which is provided by the UDPSocket. There’s also a UDPSocket example included with Xojo which I used as a reference.
To start I first decided what data I wanted to send back and forth. I narrowed it down to these actions:
These are all sent as JSON by broadcasting to a Multicast group.
JoinAction is sent when a game is first started to allow the two client NetTank apps to negotiate who is player 1 and who is player 2. The two actions are “ready” and “player2”.
MoveAction contains the action that your tank just did to send to the other client so it can update its display. Initially I was just sending actions for “forward”, “left”, “right” and “fire”. But because UDP does not guarantee messages are received, the tanks would sometimes get out of sync if a lot of moves were sent quickly when there was network congestion. So I instead decided to send the actual xy coordinate and rotation angle for a forward move so that should a message get lost it will at least have the correct information in a future forward message.
When a tank is hit, HitAction contains the new location for the tank (it is moved to a random spot on the screen when hit) to send to the other client.
Because the Combat game already ran using Timers for game handling and graphics updates, I didn’t really have to change much of the original Combat game code for NetTank. I added a UDPSocket to the main CombatWindow and in its DataAvailable event I have the code to check for the messages and update the Tank objects as needed.
I also had to make a few tweaks to the main code to send the JSON messages for movements, hits and to properly identify which tank to move.
To try the game you’ll need to run it on two different computers. The first one that starts becomes player 1 (blue) and the second one is player 2 (red). Use the arrow keys to move the tanks and press the space bar to fire.
Check out the project on GitLab.
Add your Just Code project to the week 10 forum conversation.