Using Bluetooth on Android Devices to Implement Real- Time Multiplayer Games

July 2011

Brad Boone Chris Hayes Undergraduate, Computer Science Undergraduate, Computer Science Truman State University University of Missouri – Columbia [email protected] [email protected]

Corey Darr Dale Musser Undergraduate, Computer Science Assistant Professor, Computer Science Southeast Missouri State University University of Missouri – Columbia [email protected] [email protected]

ABSTRACT methods make Android games using ad- Mobile devices running the Android hoc networks highly feasible, provided OS are becoming ubiquitous and are the developers restrain message traffic to widely used for playing games. The critical game events only. portability of these devices lends itself to the creation of multiplayer gaming using INTRODUCTION ad-hoc networking in place of external With the rise of Android as a popular network to route traffic between devices. and open-source mobile operating Since a Bluetooth radio is required in all system, development of real-time video Android-compliant devices, our team games is on the rise. The portability of chose to research the feasibility of Android devices (especially smartphones) implementing a real-time multiplayer lends itself to multiplayer gaming; game between two Android devices, however, without rooting a device, specifically HTC Nexus Ones. We developers are limited to using the investigated the effects of latency on Bluetooth wireless protocol for ad-hoc gameplay, as well as how to divide networking. Our work focuses on two- processing tasks between two phones player, real-time, ad-hoc-networked using a client-server architecture. We gaming over Bluetooth, primarily on two developed two games using modified HTC Nexus One smartphones. We set out dead-reckoning methods to compensate to show the feasibility of such games, and for latency between phones. We also to explore the issues of division of chose to limit message traffic as much as processing, latency, and network possible, to avoid possible negative infrastructure. effects from Bluetooth’s low bandwidth As part of the specification, Bluetooth capabilities. Our team recorded an only requires 800 kilobits per second average latency of approximately 20ms bandwidth—compare this to Wi-Fi, which between devices, and using the methods requires 11 megabytes per second.[1] we implemented, were able to maintain a Clearly, utilizing a low-bandwidth subjectively stable and synchronized technology like Bluetooth requires careful experience across devices. Based on these use of bandwidth. results, we found that dead-reckoning RESEARCH METHODS AND MODELS These issues raised a variety of Prototype: Pong game questions for us to address in moving The initial, prototype project is a forward. In the case of a discrepancy, simple, two-player Pong game. which perceived game state would be Essentially, each player moves his paddle correct? Did one phone need to be in using the touch screen, in order to hit a charge of shared resources, namely the ball back and forth. The gameplay itself ball? Should that duty alternate or was quickly developed and executed on a remain static? single phone, using custom game The generally accepted model for interfaces (inspired by Beginning Android multiplayer gameplay is the client-server Games)[2], as well as code written for a model.[3] In the case of two-player real- basic Breakout clone. time gameplay, the designated server In order to implement networking, device holds the true state of the game, the Pong game utilizes the Bluetooth Chat and the client stays in sync by utilizing Service class included in the sample information received from the server. Android projects with the SDK—this class An option is to make the client phone utilizes threads to listen for, set up, and totally reliant on the server phone. That maintain two-way connections over is, the server phone sends ball Bluetooth, sending data using Strings. coordinates and collision information, The game also utilizes modified handler and the client phone obliges—no local code featured in Google’s sample processing required. This approach Bluetooth Chat project. presents a variety of problems in Pong, with similar implications for other games. Division of Labor: Early Attempts In the case of the Pong game, the ball An initial vision was to give the adopts a very jerky, unstable trajectory phones as much autonomy as possible. on the client side—the client constantly Given the concrete ball-bouncing updates the x and y coordinates at mechanics, we envisioned that two games different times because of the nature of that started at a common point would the sent messages. stay in-sync while virtually independent Similarly, another attempted method —all that would be sent back and forth is to have the sever only send messages would be paddle positions. However, the when the ball starts in the middle of the inevitable latency involved with screen (or resets upon going off-screen) Bluetooth causes the two phones to and when the ball collides with a paddle quickly fall out of sync. Essentially, the or a side wall. A major issue with this players end up playing two distinct approach is a disappearing ball on the games, with no way for the games to re- client side—if the client receives a synchronize. corrupted collision message, its version of Next, we created a system wherein the ball will fly off-screen. The ball will both phones process ball physics locally reappear the next time the client receives and send messages to inform the partner an uncorrupted collision message from phone of the perceived ball position. the server. Synchronization is maintained Again, latency causes a slight lag, and a overall, but major gaps in the gameplay phone’s local ball coordinates will almost ruin the experience for both players. always differ slightly from the partner Essentially, allowing the client to be phone’s perceived coordinates. This too reliant on the server leads to an combination, applying both local inability to smooth out the issues that processing and coordinates from arise from Bluetooth latency, breaking the messages, leads to a ball that slowly illusion of a unified game and severely “floats” in a direction and zigzags around. undercutting the user experience. Thus, the client should be involved in is made, and information can flow in two processing, by assuming as much as directions between the phones. possible given the most recent data from It is at this point that the application the server. chooses one phone to act as server and one to act as client. In this game, the Network Infrastructure: Early server is chosen in a fairly arbitrary way Attempts —whichever phone’s MAC address comes In terms of networking, a simplistic first alphabetically. method, utilized in the Pong game, is to Once both players press the “Ready?” build up a custom handler class, then icon in the middle of their screens, the allow a single handler object to be shared game begins. Points are earned for between various classes. The Pong game shooting enemies, and points are lost for uses this type of network structure. touching enemies. Currently, the game However, this causes excessive and has no end and no way to “win.” unnecessary coupling between the gameplay and the sending and receipt of Division of Processing: Final Model information. This code is messy, and the Dead reckoning, as game developers overall infrastructure is too broad to be use the term, is a system whereby the effective. server sends information on important Additionally, data in the Pong game is status changes and the client estimates sent using a custom string format, with what should happen given the labels and data separated by semicolons. circumstances. For example, say an This unsophisticated format made entity, such as a player character, turns a debugging difficult. corner in-game and thus heads in a new direction. The server sends the client a Proof of Concept: Top-Down Shooter message informing the client of the The final, proof-of-concept game direction change, and the client processes works as follows: two players team up, the character moving as realistically as each as an ink-shooting octopus, to defeat possible—which varies depending on the incoming robots and earn high scores. type of game—in that direction until it Players use two virtual analog sliders, one hears of another velocity change. to move around and one to shoot in any In the top-down shooter, dead direction. The game itself is fairly simple reckoning is utilized to great effect in the —networking over Bluetooth remains the movement of the ink shots and the robots. main challenge. As it is a shooting game Whenever an ink shot or robot is viewed from above, it will be referred to spawned in the game, it comes with a as a “top-down shooter”. position and an angle. This means that To start the game, two players are when the server phone spawns a monster required. Both run the game application for the game, all it needs to tell the client and press “Start Game” which takes them is its position and angle—note that all to a “Ready?” screen. From here, a player robots move with the same speed. The can press the Settings button on his same logic works for ink shots, as well. A device to either search through a list of feature of our game is that dead paired devices to try connecting to, or to reckoning works both ways, specifically make his phone discoverable. Both with ink shots. When the client character phones are listening for connections, so creates an ink shot, the client phone sends either player can initiate the connection the server the shot’s position and angle to his partner. Once one player chooses and lets the server phone locally process his partner’s phone to connect to, the link the shot’s trajectory. Since shot information gets sent back Latency = (SenderTimeSent – and forth so often, it is quite effective to SenderTimeReceived) / 2 let each phone use its local versions of the Equation 1: Calculating Latency using other player’s shots to locally determine Local Time the other player’s robot kills. We find that when only the server is allowed to SenderTimeSent is the sending phone’s process robot kills, the client sees local time when the message is sent out, noticeable lag between when he hits a and SenderTimeReceived is the sending robot and when it disappears. Thus, local phone’s local time when an destruction works best, but the game acknowledgment is received. Each device must ensure synchronization. By performs this test once every 1000 generating and sending events back and milliseconds (1 second). When players forth when robots are destroyed, the are in the same room, latency generally devices ensure that the two players’ fluctuates about 50ms, with a high of games do not fall out of sync. about 100ms and a low of about 30 ms. The shooter also uses touch Using the most recent latency movements—on virtual analog sticks—to information, a phone that needs to send move the character. Because of the shot creation data can easily compensate constant character movement required to for the expected latency. Before sending play the game well, hundreds of touch shot data, the phone will make a copy of events will be generated every second. the shot entity, calculate where it should To cut this down to a reasonable level, we be after the latency time has passed, and implement a timer-based system, where sends those coordinates to the other each phone notifies the other of character phone. In this manner, the receiving movement every 50 milliseconds. When phone’s shots will be “caught up” with we combine this method with dead those as perceived by the sending phone. reckoning, by sending velocity information, we can fill in the gaps of Network Infrastructure: Final Model player movement—as outlined above—to At the lowest level, the top-down make gameplay look as smooth as shooter uses the same Bluetooth possible to each user. transmission classes as the Pong game, those adapted from Google's chat service Latency Compensation example program. However, the overall A difficult but essential task is dealing structure is much more cohesive. The with latency so as to keep the user top-down shooter utilizes a series of experience as seamless as possible. network classes to separate gameplay Since this implementation of the from data transmission as much as shooter game relies on synchronized possible, thus avoiding the coupling of bullets, adjusting coordinates for lag classes as is prevalent in the Pong game. proves essential. By creating layers between the game First of all, the game features timer- and the network transmission, based latency tests, whereby each phone programmers can make their code much “pings” the other. The other phone, the more cohesive, and a lot less painful to one receiving the latency test request, debug. The final project utilizes custom must respond as soon as possible. Truly classes, mainly a network interface class synchronizing two phones’ clocks is quite that shares one handler with the game difficult, so the game uses the following world, as well as sharing a separate calculation: handler with a Bluetooth connection and transmission service class. A major plus of this approach is that it makes adapting to a minimum. Programmers would also the game to another wireless technology do well to implement a custom network (such as Wi-Fi) much more feasible. infrastructure, using layers to separate Data is generally sent as custom data transfer from gameplay and prevent events, as defined by a variety of classes coupling of classes. that denote important game changes (such as a robot being destroyed or shot FUTURE WORK being fired). Using a series of handlers, The work presented here only the game application on one phone passes touches the surface of real-time data up to a network interface. At this multiplayer gaming on Android over point, data and tags are combined into Bluetooth. Our games were kept special objects defined by JavaScript simplistic, and were limited to two, and Object Notation, or JSON. only two, players. JSON objects feature mappings of keys An obvious area for future work is to values, much like a hash map, and they development of Bluetooth Android games allow for cohesive data sending with that allow three or more people to play. much less overhead than the comparable The client-server architecture would Extensible Markup Language (XML) remain, but the server would potentially alternative.[4] have to open multiple sockets and listen Finally, a small but important detail for data on all of them. Also, extra work was quadrupling the size of the write would be required to keep more than two buffer from 1024 bytes to 4096 bytes. phones in sync as they play the game. This significantly cut down on corrupted Multi-hop gameplay is also a messages, and because the buffer is possibility, but with Bluetooth, network cleared after a message is sent, instances overhead would cut into the limited, of transmission containing two jumbled critical bandwidth that is available. messages are few and far between. Although it exists outside the scope of this project, Wi-Fi gaming could be accomplished, thanks to the custom Figure 1: Effects of Uncompensated network stack. This is especially if and Latency on Client. Green circle shows when Google allows programmers to where bullet appears to be, and orange utilize Wi-Fi without rooting their circle shows where the bullet actually devices. is (according to the server). On a final note, the top-down shooter does feature code that works to resend CONCLUSION important events, by setting flags in the Since nearly all multiplayer games JSON code that denote whether a message involve shared resources and entities, a needs to be acknowledged. However, the client-server model proves essential, testing completed was not sufficient to providing unity and structure. Although speak to the strengths and weaknesses of Bluetooth features significantly less this model. Potentially, though, this kind bandwidth than Wi-Fi, it can work for of acknowledgment system could prove games, given that the developers incredibly useful—provided it does not effectively utilize event-based messaging, take up too much bandwidth. allowing the client to process the game locally given the most recent information. Additionally, a data protocol such as REFERENCES JavaScript Object Notation helps send messages that are both easy to parse and [1] Wi-Fi vs Bluetooth – Comparison low in overhead, helping to keep latency between Wi-Fi and Bluetooth. Retrieved from Optimization.” 2001. http://www.freewimaxinfo.com/wifi-vs- http://developer.valvesoftware.com/wiki bluetooth-comparison.html. /Latency_Compensating_Methods_in_Clie nt/Server_In- [2] Zechner, Mario. Beginning Android game_Protocol_Design_and_Optimization. Games, pp. 185-227. Springer Science+Business Media. 2011: New [4] Crockford, Douglas. “JSON: The Fat- York. Retrieved from Free Alternative to XML.” 2006. http://proquest.safaribooksonline.com. Retrieved from http://www.json.org/fatfree.html. [3] Bernier, Yahn W. “Latency Compensating Methods in Client/Server In-game Protocol Design and