MobiCom on Android: MinMax Games, Content Providers as Game Engines, Asynchronous Tasks, Game Engine Clients
Upcoming SlideShare
Loading in...5

MobiCom on Android: MinMax Games, Content Providers as Game Engines, Asynchronous Tasks, Game Engine Clients






Total Views
Slideshare-icon Views on SlideShare
Embed Views



35 Embeds 347 175 64 16 15 6 5 5 5 4 4 4 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1


Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    MobiCom on Android: MinMax Games, Content Providers as Game Engines, Asynchronous Tasks, Game Engine Clients MobiCom on Android: MinMax Games, Content Providers as Game Engines, Asynchronous Tasks, Game Engine Clients Presentation Transcript

    • MobiCom on Android Min/Max Games, Content Providers as Game Engines, Asynchronous Tasks, & Game Engine Clients Vladimir Kulyukin
    • Outline ● Some Background on Tic Tac Toe, ever so simple and ever so popular ● Min/Max Games ● Auto Generation & Persistence of Min/Max Game Trees ● Min/Max Game Engines as Content Providers ● Asynchronous Tasks ● Min/Max Game Engine Clients
    • Tic Tac Toe
    • Why Tic Tac Toe? ● This game was known in Roman Empire and Ancient Egypt ● Useful pedagogical tool that ties many concepts together ● Useful AI testbed with for testing various algorithms beginning from machine learning to game state search optimization: if your AI cannot handle Tic Tac Toe, it may not be not worth
    • Tic Tac Toe Combinatorics ● 19,683 possible board layouts ● 19,683 = 39 because each of the nine board cells can be X, O, or None ● 362,880 = 9! possible games, where each game is a sequence of Xs and Os of length 9 ● This is relatively simple (not as complex as chess, for example) but non-trivial
    • Tic Tac Toe Combinatorics ● In 2001 and 2002, Henry Bottomley and Steve Schaeffer proved that, assuming that X is the first to move: – 131,184 finished games are won by (X) – 77,904 finished games are won by (O) – 46,080 finished games are
    • Min/Max Games
    • Min/Max Games ● Min/Max games are played by two players: MAX & MIN ● MAX & MIN are just names that can be replaced with WHITE & BLACK in the context of names ● MAX typically moves first and then turns are taken until the game is
    • Formal Definition of Min/Max Games ● A Min/Max game is defined by the following components: – Initial state – some formal representation of the initial state of the game where MAX must move – A finite set of operators available to both players (e.g., legal chess moves) – A game end test to determine if the current state is terminal – A state utility function that evaluates the current state for both players (e.g., utility function may return 1, 0, and -1, where 1 is a win for MAX, 0 is a draw, and -1 is a win for MIN)
    • Generic Min/Max Algorithm ● Given a game state, a player, and a utility function – Use the operators available to the player to generate the set of next states – For each of the generated states: ● if a state is terminal, use the utility function to compute its utility for the player ● if a state is not terminal, switch the player and recursively compute its utility – Sort the states by utility – If the player is MAX, choose a maximum utility state – if the player is MIN, choose a minimum utility
    • Example Mk,m is k-th move from state m MAX chooses state 4 from state 1, MAX 1 u=2 because it gives a maximum utility of 2 u=n, is utility value for a specificstate M1,1 M1,3 MIN chooses state 9 M1,2 from state 4, because it gives a minimum utility of 2 MIN 2 u=1 3 u=0 4 u=2 M2,1 M2,2 M3,1 M3,2 M4,1 M4,2 5 6 7 8 9 10 u=1 u=3 u=0 u=5 u=2 u=10
    • Tic Tac Toe Game Engine as an Android Content Provider
    • Problem Develop a Tic Tac Toe game engine as an Anroid content provider. Tic Tac Toe clients can query the content provider for appropriate moves in specific
    • Plan of Attack ● Develop a Tic Tac Toe Min/Max Tree Generator (since this is a MobiCom class, we will skip this step and use an existing generator) ● Persist the generated tree (disk or database) ● Place the generated tree in a content provider ● Implement a Tic Tac Toe client that queries the content provider for optimal
    • Auto Generation & Persistence of Tic Tac Toe Min/Max Game State Trees
    • Board State Encodings Board State 1 Board State 2 Coding Conventions: row 0 x – encodes x in a cell row 0 o – encodes o in a cell ? - encodes a blank row 1 row 1 row 2 row 2 To encode Board State 1: To encode Board State 2: 1) row 0 is encoded as x??; 1) row 0 is encoded as x??; 2) row 1 is encoded as ???; 2) row 1 is encoded as ?o?; 3) row 2 is encoded as ???; 3) row 2 is encoded as ???; 4) concatenation of tree row 4) concatenation of tree row encodings gives us the encoding encodings gives us the encoding of the entire board state as of the entire board state as x???????? x???o????
    • Persisting Min/Max Game Trees in TXT Files ● While the Tic Tac Toe combinatorics are non-trivial, they are still simple enough for us the generate the entire Tic Tac Toe min/max tree and save it in a file ● The question is, what should the file format be? ● We will adopt a format where each line will have the following syntax: Line ::= Board_State;Player; MoveUtilities ● Example 01: ?????????;X;0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 ● In Example 01, the board state is ?????????; the player is X; and the move utilities are 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0, which means that if X plays 0, the utility of that move is 0; if X plays 1, the utility of that move is 1, etc. This means that Tic Tac Toe is a draw game. ● Example 02: x????????;O;4:0 1:1 2:1 3:1 5:1 6:1 7:1 8:1 ● In Example 02, the board state is x????????; the player is O, and the move utilities are 4:0 1:1 2:1 3:1 5:1 6:1 7:1
    • TicTacToe Game State Tree TXT File Here is an excerpt from a Tic Tac Toe Game State Tree file: ?????????;X;0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 x????????;O;4:0 1:1 2:1 3:1 5:1 6:1 7:1 8:1 x???o????;X;1:0 2:0 3:0 5:0 6:0 7:0 8:0 xx??o????;O;2:0 3:1 5:1 6:1 7:1 8:1 xxo?o????;X;3:-1 5:-1 7:-1 8:-1 6:0 xxoxo????;O;6:-1 5:1 7:1 8:1 xxoxo?o??;X;-1 xxoxoo???;X;7:-1 8:-1 6:1 xxoxoo?x?;O;6:-1 8:-1 xxoxooox?;X;-1 Click here to download a Eclipse project with a Java program that generates a Tic Tac Toe Min/Max game state tree and saves it in a file with the above format
    • Getting Off the UI Thread ● OK, we have figured out how to generate and persist Tic Tac Toe game state trees ● Next question, when does a content provider access those trees? ● One possible answer is to place a TXT file into /assets folder, read it line by line when the content provider app is installed, and persist each line as a record in an SQLite database ● Note that once the SQLite database is created, the TXT file can be discarded, because the content provider will retrieve all info from the database ● Since the creation of a large SQLite database is time consuming, it should be done off the main thread – enter
    • Asynchronous Tasks
    • When to Use AsyncTask ● Asynchronous tasks (AsyncTask) allow developers to get expensive computations off the main UI thread ● AsyncTasks are best suited for long one-time computations (downloads, initializaitons, etc) ● If repeated computations are required, threads, background services and other tools in java.util.concurrent should be considered
    • AsyncTask<Param, Progress, Result> ● AsyncTask is defined by three generic parameters: Param, Progress, and Result ● Param, Progress, and Result must be legal Java data types ● Param is the input type ● Progress is the progress type ● Result is the output type
    • AsyncTask Execution ● An AsyncTask is executed in four stages, each of which is done in the corresponding overriden method: – 1) onPreExecute() – 2) doInBackground(Param... input_params) – 3) onProgressUpdate(Progress... progress_params) – 4) onPostExecute(Result rslt)
    • AsyncTask.onPreExecute() ● onPreExecute() is executed on the main UI thread ● This method is used to do the setup and can complement the constructor ● If you application, for example, needs a progress bar, this method is the place to do it
    • AsyncTask.doInBackground() ● This method is invoked off the main UI thread ● This method is used to perform all background computation ● This method returns the Result type ● This step can use publishProgress() to publish progress on the main thread
    • AsyncTask.onProgressUpdate() ● This method is invoked on the main UI thread ● The timing of execution is undefined in the documentation ● This method is executed while the background computation is still in progress
    • AsyncTask.onPostExecute() ● This method is invoked on the main UI thread ● The method is executed after the background computation is done ● The result of the background computation is passed to this method
    • Implementation Details ● An implementation class must extend AsyncTask ● An implementation must, at the very least, implement doInBackground() ● Many implementations also implement onPostExecute()
    • Example // Param is String, i.e., doInBackground takes a variable array of Strings // Program is Void, which means that we will not track progress // Result is String, i.e., doInBackground returns a String class TicTacToeBoardStateDbPopulator extends AsyncTask<String, Void, String>{ protected void onPreExecute() { // do initialization on the main UI thread } protected String doInBackground(String... params) { // do processing off the main UI thread } protected void onPostExecute(String rslt) { // do post excecution things on the main UI thread } }
    • AsyncTask Cancelation ● An AsyncTask can be canceled at any time by invoking cancel() ● You can check if an AsyncTask has been canceled via isCanceled() ● It is a good best practice to check if the task is canceled in doInBackground()
    • Threading & AsyncTasks ● An AsyncTask must be created on the main UI thread ● An AsyncTask must do execute(Param...) on the main UI thread ● An AsyncTask guarantees that all callback calls are synchronized
    • TicTacToeGameCPCreator Application source code is here
    • What This App Does ● The apps sole purpose is to install a content provider that other applications can query for possible moves in a given Tic Tac Toe boards ● The app places the create of an SQLite database from a game state txt file in an subclass of AsyncTask called TicTacToeBoardStateDbPopulatorTask ● This class implements onPreExecute(), doInBackground(), and onPostExecute()
    • AsyncTask Constructor // Take a content and a reference to a writetable SQLite database public TicTacToeBoardStateDbPopulatorTask(Context cntxt, SQLiteDatabase writeDb) { mContext = cntxt; mWriteDb = writeDb; }
    • Where AsyncTask is Launched // The AsyncTask is launced into execution in onCreate() of the main activity // TicTacToeCPCreateAct // large_game_state_tree is a tic tac toe game state tree saved in /assets final static String ASSETS_GAME_STATE_TREE_FILE = "large_game_state_tree.txt"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tic_tac_toe_cp_creator_activity_layout); TicTacToeBoardStateDbAdptr.createTicTacToeBoardStateDbOpenHelper(this); new TicTacToeBoardStateDbPopulatorTask(this, TicTacToeBoardStateDbAdptr.getWriteDb()) .execute(ASSETS_GAME_STATE_TREE_FILE); }
    • The Workhorse Method class TicTacToeBoardStateDbPopulator extends AsyncTask<String, Void, String>{ // this is the worhorse method that populates the board state sqlite database through // a call to a static method of the TicTacToeBoardStateDbPopulator class @Override protected String doInBackground(String... params) { TicTacToeBoardStateDbPopulator .populateTTTBoardStateDb(mContext, params[0], mWriteDb); // see next slide return DB_CREATED; // this is a string constant } }
    • Population of DB static final String SEMICOLON = ";"; // each line in TXT file is ;-separated final static void populateTTTBoardStateDb(Context cntxt, String file_path, SQLiteDatabase writeDb) { InputStream is = null; BufferedReader br = null; try { is = cntxt.getResources().getAssets().open(file_path, Context.MODE_WORLD_READABLE); br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { processGameStateLine(line, writeDb); } } catch (IOException e) { e.printStackTrace(); }
    • Content Provider Registration ● Remember to register the content provider in AndroidManifest.xml ● We define an authority for the clients to interact with the content provider ● We also request the content provider to run in a separate process <provider android:name=".TicTacToeGameContentProvider" android:authorities="org.vkedco.mobappdev.content_providers.tic_tac_toe_boards" android:process=":org.vkedco.mobappdev.content_providers.tic_tac_toe_boards" > </provider>
    • Responding to Clients Queries ● Clients will query the Tic Tac Toe game engine content provider with the following URIs: content://org.vkedco.mobappdev.content_providers.tic_tac_toe_boards/board_state/query?board=x??0????? ● The value of the board parameter is used as the key to the SQLite Tic Tac Toe game tree database ● The db lookup is done in the query method of ● The query method returns a Cursor object to the current Contexts ContentResolver, which then passes it on to the client ● Note the synchronized db access in query()
    • TicTacToe Game Client source code is
    • Tic Tac Toe Game Client ● The client displays a Tic Tac Toe board and lets the player choose to play X or O with a menu
    • Tic Tac Toe Game Client ● The client captures touch screen clicks, draws appropriate symbols (X or O) for the user on the board, encodes the board states, queries the content provider for the optimal moves of the opponent, and draws the opponents symbols (X or O) on the board
    • Tic Tac Toe Clients CP Queries ● The clients strings.xml (see white line below) contains the content providers URI ● The client encodes the board states (e.g., x????????) and uses those strings as the values of the board parameter to query the content provider ● The actual quering is done in in the getBoardMoveUtilsByBoard() method, which uses the current Contexts Content Resolver to get a Cursor object from the content provider <string name="ttt_board_query_uri">content://org.vkedco.mobappdev.content_providers.tic_tac_toe_boards/board_state/query?board=</string>
    • Tic Tac Toe Game Client: End Game ● The client detects end games and signals them with appropriate toasts
    • References ● ● ● ● ●