An inquiry will yieldinformation about local Bluetooth devices within range, including: • Device Bluetooth address • Device “friendly” Bluetooth name, set by the user • Device class, e.g
Trang 1Developing a Bluetooth-enabled J2ME Game
Trang 2This project investigated the design and development of systems programmedusing Java 2 Mobile Edition (J2ME) Particular emphasis was placed on theanalysis and implementation of Bluetooth-based communications technology.The communications package demonstrates re-usable portions of code thatmay be used to add Bluetooth functionality to other programs The projectassesses the material in the context of a mobile game, based on the classic
“Top Trumps” card game
Trang 30.1 Acknowledgements
I would like to acknowledge the help of Dr Simon Gay, my project visor, for offering this project, and providing support along the way I wouldalso like to acknowledge the help of the DCS Computing Support service forinstalling the required development environments when needed
super-I would also like to acknowledge Chris Puncher’s Web Trumps,[17] as super-Iadapted their statistical information as test-data for my program
Jamie McHale
September 10th 2007, Glasgow
Trang 40.1 Acknowledgements i
1 Introduction 1 2 Context Survey 3 2.1 Mobile Gaming 3
2.2 Top Trumps 4
2.2.1 Top Trumps Brand Mobile Games 6
2.3 Challenges of Designing for Mobile Devices 7
3 Bluetooth Review 9 3.1 Networking 10
3.2 Device and Service Discovery 11
3.3 Authorisation and Encryption 12
4 J2ME Review 15 4.1 CLDC 15
4.2 MIDP 16
4.3 Generic Connection Framework 16
4.4 MIDlets 17
5 J2ME and Bluetooth 18 5.1 Local Device 18
5.2 Discovery and Discovery Listeners 19
5.3 Searching for Services 19
5.4 Publishing a Service 20
6 Analysis 22 6.1 Development Process 22
6.2 Requirements Capture 23
6.3 Use Cases 24
Trang 57 Design and Implementation 25
7.1 Development Tools 25
7.2 Game Architecture 25
7.2.1 Packages 26
7.2.2 Class Diagrams 27
7.3 Prototypes 32
7.4 Game Engine 34
7.5 Bluetooth 35
7.5.1 IBM Bluetooth Package 37
7.5.2 Creating a Game Encoding System 38
7.6 Graphical User Interface 39
8 Evaluation 43 8.1 Program Testing 43
8.2 User Evaluation 44
8.3 Device Evaluation 46
9 Conclusion 49 A Package <Default> 50 A.1 Interfaces 51
A.1.1 Interface Game 51
A.2 Classes 52
A.2.1 Class Player 52
A.2.2 Class RemoteListener 54
A.2.3 Class RemoteListener.StatusMessage 57
B Original Proposal 60 B.1 Introduction 60
B.2 Statement of Problem 61
B.3 Background Survey 61
B.3.1 Top Trumps 61
B.3.2 Current Software Available 63
B.4 Proposed Approach 64
B.4.1 Technologies and Concerns 65
B.5 Work Plan 68
B.5.1 Deliverables 68
B.5.2 Approximate Timetable 69
Trang 6Chapter 1
Introduction
Bluetooth is a popular communications protocol for mobile devices It can
be found on upwards of a billion units throughout the world It is found
on devices such as mobile phones, printers, earphones, and PDAs tooth is used for short range, wireless, ad-hoc communication Harnessingthe power of Bluetooth can add a great range of additional functionality toexisting programs - and opens up new doors of possibility for the future.This project investigates the use of Bluetooth in developing Java 2 MobileEdition applications
Blue-This project uses the context of developing a simple game application todemonstrate the functionality of Bluetooth The game will be programmedusing J2ME, and include wireless multiplayer functions The game that wehave selected is based on the classic “Top Trumps” card game, in whichplayers compete by having a detailed knowledge of a chosen subject area -
in particular, the statistics associated with the cards they hold
This project is useful for those who are interested in developing tions for mobile devices, and integrating Bluetooth into their systems Itwill provide a review of the J2ME language, the Bluetooth APIs available,collection of code for re-use The deliverable application will form a usefulbasis for further projects We show how an existing Bluetooth package can
applica-be wrapped and adapted for easy integration into mobile applications
This report starts by reviewing the context of development: a survey ofmobile technology, the Top Trumps card game, and a technical look at theBluetooth specification An analysis phase is then undertaken, stating goals
Trang 7sign and implementation of the deliverable is then summarised and evaluatedbefore a conclusion is reached.
Trang 8in the development process Although this project will not be sold cially, the information derived may be beneficial to other game developers.
commer-There are many mobile phone games available Most of the major phoneproviders offer a download service for games Many phones also come pre-loaded with a variety of games The current mobile phone game market
is still developing In a recent survey it was found that of the top-selling
US mobile games in the second half of 2006, none were original ‘straight tomobile’ developments Three titles were classic games, ported to the newplatform, and seven were licensed titles that were either supporting console-games, films or were marque branded[14]
Simple games, such as classic arcade games have done reasonably well onthe mobile platform But there is a lot of scope for original content to beproduced The main barrier to mobile game development appears to be thecost of development, and the risk of investing in an unknown title
There have been discussions in the media regarding the future of mobile
Trang 9phones - building up ‘characters’, or interacting with the real world in someway Mobile games may not be able to compete directly with console games,but they may be able to offer a totally different experience[3].
Top Trumps is a classic card game, which rose to popularity during the1970s and 1980s It involves both a simple game-play element and a ‘collec-tion’ element
Many sets of Top Trumps cards have been produced Sets of cards arebased around a particular theme These themes may be as diverse as cars,aircraft, historical figures, or sea-life Each card is described by a set ofstatistics, shared by all of the cards in the set
Figure 2.1: New Rockets: 1982 Waddingtons Series
For example, the Waddingtons 1982 “New Rockets” set defined the lowing five statistics for each rocket:
Trang 10The game-play is centred around choosing a statistic to challenge an nent - the ’winner’ of the round being the player with the higher value cardfor the chosen figure.
oppo-The collection occurs either during the game, winning your opponentscards, or after where the winner collects ‘ante’ cards A player, throughwinning or obtaining new cards can build up their deck of cards, collectingeach card in that particular set The strategy in the game play is building
up knowledge of the statistics for a set of cards - knowing what constitutes
a ‘winnable’ statistic
Top Trumps has a simple transactional game-play structure:
• The available cards are dealt among the players equally
• A player starts the game by selecting a category from their ’topmost’card, reading out the value of that category
• The second player responds with their statistic for the chosen category
• The winner of the round is the person with the highest value for thatchosen category
• The winner of the round adds his or her opponents card to the bottom
of their playing deck If a draw occurred then the two cards are heldinto the next round, increasing the winning stakes
• The winner of the round then chooses the category for the next round
• The overall winner is the person who collects all of the cards
There are many variations on the top trumps game:
Three Card Pick In this variation when a player only has three cardsremaining they get a chance to pick a card to play, rather than it being theirtop-most card The main effect of this is to extend the game-time
Super Pick Traditional Top Trumps cards came in decks of 32 cards Theywere labelled A1-A4, B1-B4 G1-G4 Per deck there was one “super pick”card that beat all other cards, with the exception of cards labelled with a ‘1’
Trang 112.2.1 Top Trumps Brand Mobile Games
There are several “Top Trumps” brand games available, both for the bile gaming platform, and for others such as Nintendo DS[5] Top TrumpsGumball 3000 Supercars Mobile is a Java-based game for mobile phones Ithas a humans vs CPU element, and a human vs human over Bluetooth ele-ment It includes “lifelines”, functions that modify the game-play, extendingthe game and making the strategy more complex
mo-Figure 2.2: Gumball 3000 Supercars UI
Figure 2.3: Top Trumps Live Sharks UI
Top Trumps Live: Sharks Top Trumps offer simple Top Trumps games
Trang 12Flash There are several sets to play, including sharks, cricket stars andhorror The graphics aid in the game-atmosphere, bringing the cards to life:
De-vices
The context of this system is a mobile phone, or other limited device.There are several problems that need to be overcome when designing forlimited devices[11], such as limited program resources, and differing userexpectations
When interacting with a mobile phone a user will have a different rience and different requirements than when interacting with their desktopcomputer Their tolerance of failure is reduced - they don’t want to re-boottheir phone when in the middle of an operation or transaction Interfacesneed to be highly responsive, and tuned for the specific functionality of theapplication
expe-Mobile devices by their very nature have a limited set of user interfacefunctionality The devices are highly constrained both in terms of input andoutput Mobile devices normally only display one “screen” at a time, withonly vertical scrolling enabled Windowing systems, prevalent on desktopcomputers are absent from mobile devices
J2ME provides some levels of abstraction for creating GUI elements Ahigh level abstraction defines user interface elements, but leaves the actualgraphical representation and layout to the device A developer may specifythat a form must contain a text box and a button, but it is the devicemanufacturer that will specify how these elements look and behave
Lower level abstraction uses specific painting techniques and “canvases” todraw on the screen Algorithms are used to adapt the painting to differentdevices Designing with a high level of abstraction means that the programwill work on a larger range of devices than with lower levels of abstraction,
as all devices supporting the configuration will support the widgets - whereasyou may have to design for specific devices when drawing on canvas objects
Trang 13Figure 2.4: SUN JWT: Example GUI Widgets: ChoiceGroup
The other consideration, as well as constructing a GUI, is the level ofuser input that is attainable Mobile devices are constrained in terms ofkeyboard and pointing device input It is only very recently that tactile,touch-sensitive devices, have become available on the market Users ofteninput to devices using only one hand, and with a limited number of keys.Joysticks and other directional pads may be used, but cannot be relied upon.This often means that the user input is slower than on traditional devices.Users expect functions to require as little manual input as possible - withcommon functions being assigned to keys, or to menu commands Free textinput is one of the slower ways of providing input, and should be avoided ifthere is a widget or command that functions better
J2ME provides a level of abstraction for user input, allowing the mapping
of physical keys to abstract commands It is up to the device vendor ashow to interpret the request for command objects Certain object may beassigned to device-specific keys, others to screen elements Developers canstate preferences, but not have any guarantees about UI interaction
Trang 14Chapter 3
Bluetooth Review
Bluetooth is a connectivity technology for creating Personal Area Networks(PANs) The Bluetooth specification uses a short range radio standard toimplement its communications protocols Bluetooth provides a simple andefficient way of connecting devices in close physical proximity It can be found
in devices such as mobile phones, PDAs, laptops, printers, games consolesand digital camera
Around 13 million Bluetooth-enabled units are produced ever week, withfive new Bluetooth-enabled products being qualified every working day[18].Bluetooth is being included on most new mobile phone handsets being pro-duced by companies such as Nokia and Sony Ericsson Intel is adding Blue-tooth capabilities to several of its products
Bluetooth is a popular technology thanks to its low power requirements,open-standards, and in-built security measures The range of the devices
is appropriate for most local wireless applications: approx 10m, however,ranges of up to a mile have been tested by engineers
Figure 3.1: Bluetooth Logo
Trang 15The Bluetooth specification is managed by the Bluetooth Special InterestGroup (SIG) The SIG was founded in 1998, with five members By the end
of the year over 400 members had signed up[18] The name “Bluetooth”was adopted in honour of the late tenth century King Harald Bluetooth ofDenmark and Norway He was known for his unification of the Scandina-vian countries, and it is unification of devices which is the main aim of theBluetooth specification[2] The Bluetooth SIG now has over 9000 membercompanies, producing Bluetooth branded products The member companies,including Ericsson, Intel, Lenovo, Microsoft, Motorola, Nokia and Toshiba,all have influence over the direction and development of the Bluetooth spec-ification
Development of the Bluetooth specification began in 1994 Version 1.0 ofthe Bluetooth specification was released in 1999, a year after the formation
of the SIG Within a year Bluetooth was already being embedded in a variety
of devices, within three years over 500 products were Bluetooth qualified In
2004 the Bluetooth SIG adopted version 2.0 of the specification, featuring anenhanced data rate amongst other features
With so many powerful companies backing the specification, Bluetooth issure to remain one of the dominant mobile communications protocols for theforeseeable future
Bluetooth devices network with other devices on an ad-hoc basis cally they create piconets A piconet is a network based on a master/slavedevice relationship The Bluetooth specification directs that a Bluetoothpiconet can be one master with up to seven slave devices Two or more pi-conets can be combined into a scatternet by a slave device switching betweennetworks, or a master device having a slave role in another network
Techni-The Bluetooth specification also allows for up to 255 dormant devices onthe piconet, which the master can make active at any given point
One reported problem with Bluetooth development is that device providersoften deviate from the standard when implementing the networking capabil-ities Devices may not have full support for seven slaves, or the ability toswitch roles Application developers must be aware of their target platform,
Trang 16Figure 3.2: An example of a Bluetooth scatternet, with a shared slavedevice[6]
and provide work-arounds or different versions of the program depending onthe features available
Bluetooth networks are ad-hoc and are often chaotic as many devices move
in and out of Bluetooth range A Bluetooth implementation requires amethod of searching for devices, and finding out the capabilities of thosedevices
Device discovery is known as an inquiry operation An inquiry will yieldinformation about local Bluetooth devices within range, including:
• Device Bluetooth address
• Device “friendly” Bluetooth name, set by the user
• Device class, e.g Mobile phone, laptop, headset
• Technical information on the device
Once a Bluetooth device had been found then a list of services that the
Trang 17A Bluetooth device can perform a general discovery to obtain a list of allservices that another device offers, or it can filter just the services that itrequires.
A Universally Unique Identifier (UUID) is assigned to each service SomeUUIDs are pre-assigned by the Bluetooth SIG, others are generated by devel-opers at the time of implementation The UUID provides an easy ay for twoinstances of the same application running on different devices to recogniseeach other
Once a service has been discovered then the device can open a connectionand exchange data
The Bluetooth specification allows for both authentication and tion across the wireless connection Services can be advertised as requiringauthorisation, authorisation and encryption, or neither
encryp-Bluetooth devices can use a technique called pairing to establish a tionship of trust A passkey is shared between the two devices by the user.The devices can then authenticate and verify the identity of the other device.Users may be prompted if they wish to allow a device access to theirservices even if pairing is enabled Some device manufacturers allow accesswithout pairing based on the type of transaction that is taking place Ex-amples of this may be OBEX (Object Exchange) business cards or notes.The ability to send messages without authentication has led to the rise ofbluejacking - where users receive unwanted, and often anonymous, messagesfrom local devices[8]
Trang 18rela-In November 2003 security concerns were raised over the disclosure of sonal information by Bluetooth devices Specific vulnerabilities included[7]:
per-• Confidential data, such as the phonebook and calendar may be accessedanonymously and without the users consent
• The complete memory of some previously paired ‘trusted’ devices could
be accessed even when the device had been removed from the pairedlist
• Access to the higher level commands of a mobile phone device may beobtained, giving access to voice and data messaging functions
These problems were found to be of the specific implementation by devicemanufacturers and not with the Bluetooth specification itself Lists of theaffected devices remain published online[7] The Bluetooth community areworking with device manufacturers to resolve these potentially disturbingproblems
Figure 3.3: A Bluetooth authorisation prompt: Sun JWT Grey Phone
Trang 19Another consideration has to be given to security on Bluetooth applicationsthat wish to use the local Bluetooth features: most devices require explicitauthorisation from the user for access to the Bluetooth stack If a programtries to access the stack, and has not been previously authorised then thedevice will jump out of the program and display a confirmation alert to theuser The user often has the option of indefinitely authorising the MIDlet touse the stack - but this is dependent on the device Java implementation.
Trang 20Chapter 4
J2ME Review
Java 2 Micro Edition (J2ME) is a version of the popular Java programminglanguage, designed to run on devices with limited resources It runs on ahierarchy of configurations, profiles and optional packages It uses subsets ofthe Java Standard Edition APIs, but often scaled down, or made efficient forresource-constrained devices
Connected, Limited Device Configuration is a term for one of the definedconfigurations of device implementing basic J2ME APIs A configurationprovides the basic set of features that must be present in the implementation
of the J2ME environment[10] Configurations are an easy way for developers
to ensure that a particular device will support their application
CLDC is a basic configuration specified on grounds of processing power,input and output capabilities and networking functions CLDC is one of themost basic configurations, with only a 16-bit CPU, 160 KiB memory and alimited network connection required
There are three general APIs that are available on CLDC:
• java.io - Input/Output operations
• java.lang - Java types, system and security functions
• java.util - Collections classes
Trang 21The value in specific device configurations, such as CLDC, are in the factthat the programmer has easy access to specific functions, without the over-head of implementing APIs for functions the device does not support.
The Mobile Information Device Profile (MIDP) is one of the many profilesthat can be built on the CLDC configuration Profiles represent a set of APIsthat are implemented on a subset of devices within a particular configuration.Profiles can be extended by optional packages, a collection of APIs specific
to a particular technology One optional package that we will investigate isthe JSR 82, the Java Bluetooth API Other optional packages include thosefor Wireless Messaging, or Mobile Media
MIDP is currently on version 2.0, with version 3.0 currently being ered The first MIDP devices were launched in 2001
consid-There are several useful Java classes contained within MIDP, most of whichmobile application developers should be familiar with:
• javax.microedition.io - Specific Input/Output operations
• javax.microedition.lcdui - User interface functions, based on theconcept of single “screens” This class defines a number of standard
UI “widgets”, such as Lists, Alerts and Text-boxes There are differentlevels of abstraction available from high level forms and widgets, down
to specific painting routines on the canvas classes
• javax.microedition.rms - Record Management System
• javax.microedition.midlet - Forms the basic classes for ming a J2ME application
The Generic Connection Framework (GCF) is a J2ME API that providedsupport for several functions that are handled by the java.net and java.ioAPIs in J2SE GCF is designed to rely on the CLCD configuration GCF isnow included in many configurations and profiles
Trang 22The GCF provides a level of abstraction so that data connections of ent types can be implemented There are several basic interfaces that extendthe base Connection class:
A MIDlet is a basic J2ME program package Each deployable J2ME gram comes in a jar file, packaging both the classes and resources that theprogram needs The distribution should also come with a Java ApplicationDescription file, detailing attributes of the application
pro-The JAR file needs to go under a pre-verification process after compilation.When Java 2 Standard Edition (J2SE) programs are run the Java VirtualMachine verifies the program before it is run There is a reasonably sub-stantial overhead in doing so, which would not be suitable for devices withlimited resources
Pre-verification performs some checks on the MIDlet before it is deployed,thus reducing the processing burden on the device MIDlets have annotationswithin their code as marked by the pre-verifier, so that the device can be surethat the code has undergone the process
Trang 23Chapter 5
J2ME and Bluetooth
J2ME provides several classes to aid developers in adding Bluetooth
func-tionality to their applications These classes are contained within the javax.bluetoothpackage The classes are used to gain information about the Bluetooth ca-
pabilities of the device on which the software is running, seek other devices
and services, then make and receive connections
One of the fundamental aims of this project is to implement a reusable
package and interface, and design and demonstrate a wrapper class that can
easily be re-factored for use in a different program The following information
will be useful for anyone wishing to delve beyond the interfaces and into the
classes that will actually do the Bluetooth programming in our game
The LocalDevice class provides the basic functions for gaining information
about the Bluetooth capabilities of the host device These functions include:
getBluetoothAddress(); - String
getDiscoveryAgent(); - DiscoveryAgent
getFriendlyName(); - String
The Bluetooth address is set by the device itself The “Friendly Name”
is set by the user The friendly name normally defaults to the device name,
e.g “Sony Ericsson k800i” The function returning the DiscoveryAgent is
the way in which discovery services can be accessed
Trang 245.2 Discovery and Discovery Listeners
The Discovery Agent is responsible for the discovery functions of the localdevice To access the DiscoveryAgent class you must get the LocalDevice,from a static method of the LocalDevice class and then retrieve the Discov-eryAgent:
DiscoveryAgent mDiscAg =
LocalDevice.getLocalDevice().getDiscoveryAgent();
A DiscoveryAgent contains the functions that start and stop a deviceinquiry, and can register classes implementing the DiscoveryListener interfacefor call-back on several discovery related events A class implementing theDiscoveryListener interface must have the following methods:
• deviceDiscovered(RemoteDevice rd, DeviceClass dc) - Fired when
a device is found during an inquiry The RemoteDevice object yieldsthe same information as the LocalDevice class, and can be used to set
up connection details
• inquiryCompleted(int discType) - Fired when the inquiry phase iscompleted, either due to a timeout as per the device default (set bythe manufacturer, adjustable by the user in some cases), or by a cancelmethod call on the DiscoveryAgent
• servicesDiscovered(int trans, ServiceRecord[] svRc) - Fired when
a service search finds new matching services The service record arrayholds details of these services for further interrogation
• serviceSearchCompleted(int trans, int respCode - Fired when aservice search is completed
There are several techniques that may be used when searching for devicesand services Each of these varies in processing requirements, functionalapplication requirements, and the complexity of code required for implemen-tation
Trang 25The method with the highest reliability of yielding the intended results (i.e.discovering a device with a specified service) allows the Bluetooth search tocomplete, and then searches the services of each device This may take severalseconds, depending on the Bluetooth implementations of the devices that areinvolved Once a search has yielded results then the program or the user canchoose the specific device or service that they require.
A quicker method used by some programmers is to initially perform aservice search, without explicitly specifying a device search to precede it.The result of this is that normally the first matching service to be found isused, rather than presenting a list of options to the program
Programs may also terminate a device search after a particular period oftime The list of devices and services can then be retrieved by passing thestatic identifier ServiceRecord.CACHED to the retrieveDevices() method
of the discovery agent The agent will then use devices that are stored in thememory
There is always a risk in using this method that the devices or servicesthat you are seeking do not respond in time Care must be taken to ensurethat an application developer considers the required robustness and flexibility
of the final system as well as response time
Roaming or “social” applications may make use of this service search ture where it doesn’t matter which specific device you are connected to - infact, there may be some benefit or not choosing - e.g date finder, socialnetworking software
Publishing a service record is easy with J2ME The MIDlet needs to ister a Service Record in the Service Discovery Database The GenericConnection Framework is used, and a StreamConnectionNotifier object
reg-is created The connection object then opens a software connection to thelocalhost, using the UUID of the application Other details can be included
in the localhost connection URL, including requirements for authorisationand encryption
The connection to the SDDB then needs to be monitored to handle ing connections A worker thread continuously polls the StreamConnection-
Trang 26incom-it can be passed on to a processing method which can open an InputStream
or a DataInputStream object to process the incoming messages
Trang 27Chapter 6
Analysis
The Analysis Phase of the software development cycle is important: itdefines the scope of activity for the following design and implementationphases, and provides the yardstick against which evaluations are measured
In this phase we will look at the development process as a whole: techniquesthat we will use, and modifications to the standard models We will then look
at the elicitation of the project requirements, define Use-Cases as metrics,finally looking at the development tools that will be used in the process
It is important to establish a development process as a framework forguiding a projects work In this project we based our process on the Waterfallmodel of development, with the addition of an iterative prototyping phase
1 Proposal (Feasibility Report)
2 Analysis of Context
3 Analysis of Technology
4 Requirements Capture
5 Generation of Use Cases
6 Iterative design, with prototyping
7 Final implementation
8 Testing
Trang 28Our prototyping phase will allow us to generate tests for the different areasand packages of our program before implementing the final design It is inthis phase that we design small Bluetooth example programs to ensure thatour understanding of the technology would allow us to build an efficientinterface and adaptor classes for our game.
The Requirements Capture phase is where the system requirements andconstrains are elicited, and the application domain defined Key stakeholdersprovide input and a course of action is agreed upon
In this project there is only one stakeholder; Dr Simon Gay, project pervisor Within the context of this particular project it was appropriate todetermine project requirements from a series of talks and discussions Theproject scope is reasonably large: the main purpose to evaluate the use ofBluetooth on mobile devices An initial set of targets were agreed on, andthen refined throughout the project as implementation hurdles were encoun-tered
su-The initial project targets can be described as functional requirements,specific tasks that the final deliverable must be capable of:
• Project must develop a mobile-phone based game
• Game must use Bluetooth technology as a tool to transfer information
• Game must have multiplayer functions
In addition to the functional requirements, we also have a set of functional requirements These describe project constraints that are separatefrom the deliverable system These are:
non-• The Project Report must be completed by the 10th September 2007
• The software system must be demonstrable by 3rd September 2007
We will revisit these requirements in the evaluation phase, in which we willcompare our final results with our expected targets
Trang 29• Connect to a Remote Game
• Host a Local Game, allowing remote connections
• Display the currently connected game status
• Register a move with the current game
• Disconnect from a game
If each of these Use Cases are implemented then the game as a wholewill be functional There are a subset of requirements that the game-logicdictates, however, they are individual functions and not worthy of examining
at Use Case level, e.g each card must have an image associated with it; thecard data should be loaded from a text-file
Trang 30Chapter 7
Design and Implementation
The focus of this project is on demonstrating a Bluetooth-enabled mobilegame Once the context of the project had been analysed the demonstrationsystem was designed and then implemented We firstly selected our develop-ment tools in order to design and build the application Using an iterativeprocess we produced models of the system - and then implemented it in Java
By the end of this chapter each of the components of the final system willhave been described The source code is included on an accompanying CD,and an overview of the Bluetooth-wapper classes, the game interface, andthe player class are included as appendices to this report
For the project we used a variety of tools We had an IDE for developingthe Java code, with specific plug-ins for developing MIDlet suites
• Eclipse
• Sun Java Wireless Toolkit (with device emulators)
• Eclipse ME plug-in for Eclipse integration with JWT
• Sony Ericsson k800i, Nokia N80, Sony Ericsson k750
Trang 31diagrams we can develop a series of visual models of the system, describingthe packages, classes, fields and methods that are pieces of the final puzzle.
We have used UML models, as they allow a simple, easy-to-understand andabstract description of the system By keeping a high level of abstraction
we can design a highly modularised system - allowing us to pull out ourcommunications classes for use in other projects - or drop in new versions ofthose classes (via interfaces) as new technology becomes available
We will firstly describe the system in terms of packages, before goingthrough a series of refinements, resulting in the production of detailed ClassDiagrams
7.2.1 Packages
Figure 7.1: Package Diagram: Overall System Model
Our package diagram shows three main constituent components:
Trang 32• Game Engine and Logic
• Communications
• Graphical User Interface
Each of these packages is responsible for a specific group of functionaltasks These tasks are dealt with by the classes within these packages
The Game Engine implements the rules of the game, contained within thegame logic The Game Engine deals with both the core game, and the playersthat connect to that game Different versions of the classes are shown forimplementing the logic of a “hosted/local” and a “remote” game
The Communications package sets up and manages Bluetooth connections
It will send, receive and interpret all game messages It will respond torequests from remote devices It is shown collaborating with the both thegame and player classes - as it will have to deal with each depending on whichside of the communications connection it is on
The Graphical User Interface package is responsible for working with thegame display This includes game menus, and the actual display of gamestatus It will collaborate with the player class, from which it will derive allnecessary information It will not collaborate with game classes, in order tominimise specific coupling between packages
7.2.2 Class Diagrams
A Class Diagram shows the fields and methods of each class in our system
We will look at each package in turn, and for reasons of clarity and simplicity,developing the class diagrams in an iterative fashion, adding detail as we goalong
Firstly, we will examine the basic Class Diagram for the Game Engine.The principle behind the existence of these classes is to provide a cohe-sive, simple and logical set of objects, modelling real-world game play Wemust also factor in considerations about the design functioning over a remotecommunications link With this in mind, the following classes are illustrated:
Trang 33Figure 7.2: Class Diagram outline: Game Engine Package
These implementations are the RemotePlayer and the LocalPlayer Wedid not include them on class diagrams on this report for clarity
• Game, an interface Defines the basic functions that a game mustimplement
• RemoteGame, implementing the game interface Works as a holder, waiting for information from a game on a remote device There
place-is no game logic implemented in a RemoteGame
• LocalGame, implementing the game interface Contains game logic,constructing the rules of the game Accepts input from two Playerobjects, but is unaware of whether the players are being controlledremotely or locally
• CardSet, contains a collection of Card objects Responsible for loadingCard objects from a file
• Card, contains information on a specific playing card, including title,image, description and statistics
Trang 34Now that we have an understanding of the basic functionality of the game
we can add in a set of fields and methods for each class, that will help usunderstand its role in providing functionality and value in the system
Figure 7.3: Game Engine Class Diagram: Detail
The Game Engine Class Diagram detail shows the fields and methods wecan describe for the player class and the game interface Also shown are theCardSet and Card class fields and methods, however, these are not central
to the design of the game, and will not be described further in this section
The Game Interface is mainly composed of accessor methods There is
an accessor method for every variable that is a constituent part of the gamestate By describing each of these variables were can completely describe thestate of the game at the time of examination These variables are:
A set of boolean values indicating the basic state:
• Is the game running? The game may be awaiting a player, or processingthe set-up methods
Trang 35• Is the specified player the “active” player in the current game? Whenthe player is “inactive” they are waiting on their opponent for input.
• Has the specified player won the game? Before the game is over this
is false for both players Once the game has completed then it will betrue for one player, false for the other, unless it is a draw, in which case
it will remain false
A set of numbers give the remaining game state details:
• Game Card Set ID Number
• Current Card ID for the specified player
• Pile Size for the specified player
• Pile Size for the opposing player
• An integer identification number for the last move made, in order tosynchronise updates across remote devices
The Game interface also provides two methods that modify the game state:
• Get a Game Slot - A method that a player object can call (passingitself in the methods parameters) requesting to join the game Shouldthere be an available slot (two slots for a local game, one for a remotegame) then the method will return a “true” value, otherwise a “false”value The player object is then able to determine whether or not itcan start playing in the game
• Move - Allows a player to submit a move to the game engine Themethod has two parameters, a player object (to easily check whichplayer has called the method) and an integer choice, representing thecard statistic which has been decided upon
The Player Class will interrogate their Game Object (whether Local orRemote) to derive their standing in the current game All of the playermethods function as adaptors, allowing access to the game state
How do the game engine classes interact with out communications package?
We saw on the original package diagram that the communications packageinteracted with both player objects and concrete game objects
Trang 36Figure 7.4: Class Diagram Detailed: Game Engine Package
We defined the communications classes in terms of a Bluetooth listenerinterface, and a wrapper class that will control our game functions Thewrapper class that adapts the Bluetooth messages to our game functions isthe Remote Listener In this context the RemoteListener performs one oftwo functions, depending on the constructor method that is called:
• A listener for a LocalGame that awaits a connection from a remotedevice, then controlling a RemotePlayer in that game
• A listener for a RemoteGame that is given a connection to a remote
Trang 37This adaptor class, in essence, provides the two sides of the game protocol.
It receives and interprets Bluetooth messages, and then calls the appropriatemethods in the game
The advantage of not having separate listener classes for dealing with each
of the client/server (hosted and connected) games is that if the encoding ofthe information over the connection changes then only one class needs to beupdated
The RemoteListener class implements the BTEventsListener interface - afront-end for a Bluetooth communications package developed by IBM Wewill examine this in the Bluetooth implementation section
The RemoteListener class contains a dependent class: the StatusMessage.This embedded class composes and decomposes status messages for trans-mission The details of this class will also be discussed in a following section
Now that we have a basic concept for the game architecture we can beginthe implementation phase
The complexity of this project leant it to having a prototype-buildingdevelopment iteration We had to consider both the game-logic, as well ashow to implement the program on a mobile device By separating out thesetwo development strands, and running prototype models of each we were able
to learn valuable lessons that shaped the final product
There were two main prototypes The first focused on developing thegame logic in J2SE, the second on testing user-interfaces in J2ME
The first prototype was a game engine developed in Java 2 Standard tion This helped with the understanding of the game mechanism Thetechniques and algorithms for allowing players to join the game, and thesteps for allocating cards, and processing game information were elucidated
Edi-The translation processes from J2SE to J2ME was fraught with difficulty.J2ME does not include some of the useful libraries for representing collections
of data Efficient classes for the storage of card data had to be developed
Trang 38Figure 7.5: Prototype Development Route
The second prototype followed on from the development of the J2ME gameengine A mock-up interface was created This included the display of a cardtitle, a card image, and a menu of statistics When the “fire” button waspressed then a move was submitted The menu system had to be programmed
to highlight the correct menu item, based on user input with the abstract
“up” and “down” buttons
Whilst the GUI development was taking place the Game Engine was tested
on a “command-line” interface style of interaction This allowed us to checkthat the game engine was functioning correctly, before tying it to the GUI
In this was we could be sure that the problems identified were those of theengine, and not those of the GUI, or with the GUI/Engine coupling
Trang 39Once the basic game engine had been developed, and tested using lated players, they were tied to a Bluetooth communications class This will
simu-be discussed in the following section
on a game running n a remote device
As discussed above, a simple J2 Standard Edition prototype was structed for the game engine But what other issues were dealt with duringthe production of the game engine?
Representing Cards
Representing the game cards is an integral part of the game engine package.There were two main considerations that we had to make when designing andimplementing the classes:
• The cards and card-set information should be loaded from a separatefile, in order that different sets of cards may be easily bundled with thegame
• The card information should be able to be represented in a sufficientlycompact was as to facilitate easy transfer via a Bluetooth connection