ai dominoes project

42
Page 1 of 42 City University London BSc Business Computing Systems Final Year Project Report Academic Year: 2014-15 “ Development of an AI Engine in the context of prototype Dominoes game for android device” By Adil Gasimov Project supervisor: Dr Peter Smith 7 th May 2015

Upload: adil-gasimov

Post on 11-Apr-2017

377 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: AI Dominoes Project

Page 1 of 42

CityUniversityLondon

BSc Business Computing Systems Final Year Project Report

Academic Year: 2014-15

“ Development of an AI Engine in the context of prototype Dominoes game for android device”

By

Adil Gasimov

Project supervisor: Dr Peter Smith

7th May 2015

Page 2: AI Dominoes Project

Page 2 of 42

Abstract: The aim of this project is to simulate dominoes game by implementing an artificial

intelligence engine for the famous Dominoes 101 game. A domino 101 is a table

game consisting of 28 bones with two sides. In each side of the bone there are from 0

to 6 dots (there are 7 of each number). Player with the highest double will start the

game. Game is a chain of dominoes connected to each other by the similar side

(similar number). If player or AI does not have the corresponding move, then they

draw till they get the right bone. The player with first empty hand is going to win. At

the end of each round the number of dots in the opponent’s hand are counted as a

score, and the game is being played till one of the players reach the total score of 101.

The two main strategies of playing the game is to determine your opponents tiles and

identifying the weaknesses. I will construct a decision matrix of 7X7 and let it to be

self-updating after each move. Programming language is going to be Java.

System requirements are:

1. Android Studio 1.0.1

2. Emulator

Page 3: AI Dominoes Project

Page 3 of 42

Table of Contents

Abstract:...............................................................................................................2

CHAPTER 1: INTRODUCTION:........................................................................4Problem to be solved...........................................................................................................................................5Scope limit..............................................................................................................................................................6Project Beneficiaries............................................................................................................................................7Summary of results..............................................................................................................................................7

Requirements:.......................................................................................................................................................7Implementation:...................................................................................................................................................7Testing:....................................................................................................................................................................8Project Report:.....................................................................................................................................................8

CHAPTER 2: LITERATURE REVIEW:.............................................................9

CHAPTER 3: METHODS:.................................................................................12Requirements:.....................................................................................................................................................13Design:..................................................................................................................................................................13Artificial Intelligence (AI):............................................................................................................................16Testing...................................................................................................................................................................18Evaluation (maintenance):..............................................................................................................................18CHAPTER 4: RESULTS:...................................................................................19Introduction:........................................................................................................................................................19Requirements:.....................................................................................................................................................19Design:..................................................................................................................................................................20

Home Screen:....................................................................................................................................................20EnterTheNameScreen:...............................................................................................................................20Game Screen:....................................................................................................................................................21Winning Screen:...............................................................................................................................................21Home Screen:....................................................................................................................................................22Enter The Name Screen:................................................................................................................................22Game Screen:....................................................................................................................................................23

Testing:..................................................................................................................................................................35Evaluation:...........................................................................................................................................................36Conclusion:...........................................................................................................37FutureImprovements:..................................................................................................................................37Personalexperience:......................................................................................................................................38Works Cited........................................................................................................39

Page 4: AI Dominoes Project

Page 4 of 42

CHAPTER 1: INTRODUCTION:

First patterns of AI in the gaming sphere have appeared in 1950, when computer has

just become programmable. Claude Shannon and Alan Turing wrote one of the first

AI engines for chess game. However AI critics have been criticizing the AI, by saying

that it is impossible for AI to make decisions and have a proper choice like human

being. Even though player adds a little uncertainty to the whole equation of the

sequence, the table games are mostly perfect information games, as computers get full

information access about the all the state of the game. Up to these days table games

are counted as the natural test bed for the algorithms and area of academic research,

and still remain like this. (Middleton 2002 ).

There are various genres of games such as action, strategy, RBG, simulation,

adventure and the “Dominoes 101” game I am going to develop will match to the

strategy genre in which an AI is going to challenge a player. (wikipedia 2015). In gamming,

AIplays an important role as it involves continues interactions/learning from the

environment. Game such as Dominoes (strategy game) involves high use of

mathematical calculations, app design, algorithmics and AI. My overall aim is to:

“create an AI engine for the prototype table game, where AI is going to challenge

players ,by decreasing their chance of having the next move”. AI will involve several

methods, which is used for the common decision matrix, where each bone is assigned

a value. Values given to the bones are going to be changed after each move by the

help of “UpdateTheBoard” function.

Below shows my objectives:

• I will design my interface (GUI) to determine how the game will appear on a

screen.

• I then plan my implementation out, for this stage I will consider using Android

API to design this game.

Page 5: AI Dominoes Project

Page 5 of 42

• Then I need to develop an engine, which is capable to adapt to the current

situation and map the logics in to objects. I am planning to do it with the help

of “Android Studio” and online materials extracted from the web site”

www.developer.com” with tutorials.

• When implementing I should try to minimize compiling errors.

• Test and evaluate my project to see the behaviors of my agent. If the agent

acts, as it requires then my object is met, else I will change the code

accordingly.

• At last I will document my project, to do this I will design diagram using

‘Mockups’, design GUI in android simulation.

Problem to be solved

Lack of expertise in developing of an AI engine in Java leads to a very little amount

of helpful resources could be found on the Internet. Books such as “AI Game engine

programming” by Brian Schwab and few web sites based on training and guiding

developers through the programming are more supportive in this way. Domain issue

requiring a close approach could be divided to two parts. First approach is minimizing

problem of uncertainty, when second one is the estimation. AI engine should be

similar to human brain in the specific area of application and emerge required

algorithms with different specifications. Searching through possible moves and

deciding which move is most appropriate for that particular time is very important.

Thinking few steps ahead relying on the past moves is also one of the key concepts of

artificial intelligence engine. Calculating the probability using mathematical

algorithms in order to diminish the opponents harm require relatively more time

among the other parts such programming and design.

According to [2] there are five requirements, which are needed to be supported to get

an effective artificial intelligence engine such as reactivity, context specific,

flexibility, realistic and being easy to develop. Each of these agents must be supported

by well-designed components of an AI engine. However the main component of an

AI engine is inference machine, which allocates needed knowledge to the current

position.

Page 6: AI Dominoes Project

Page 6 of 42

Testing is faced almost in each phase of the programming and it needs to be done

either with emulator or an android device as our prototype game is for android device.

Problem with emulator is that it is very slow and could take more time than we have.

Therefore purchasing an android device can be another problem in the financial terms

by increasing the budget of the project. As a summary of all the listed difficulties I

would like to mention that all the components listed above depend on each other and

work time on the project should be separated efficiently among all parts.

Scope Limit

It is harder to tell about the possible risks at the start of your work on the projects.

However according to my chosen sphere I would most probably have timing problem

as the projects is very high dense project. AI development with Java requires patience

and hard work by going through through genetic computing; logic based reasoning

system and Java representation for predicate calculus.

In order to minimize the damage from time limit I will try to separate enough time for

each section and spend more time on the most time demanding sides such as:

programming, design.

I will find similar projects to mine and see the volume of the project and step taken to

overcome similar type of problem. As I have talked about it in the first paragraph lack

of resources is another risk for the project. Most of the developers prefer working on

C++ and use their tools. However I chose to program my app with Java, as I know

Java basics, which will speed, up my activity.

Solution to lack of resources problem is that what actually matter is quality, but not

the quality. Even though it took some time to find the required materials I have

enough to go with right now.

Page 7: AI Dominoes Project

Page 7 of 42

Project Beneficiaries

Association of people or entities to whom my project might be attractive are mobile

application developer companies and young, enthusiastic and starting developers in

the sphere of AI.

Artificial Intelligence engines all differ in the ways of programming method and

approaches on recognizing, remembering and reusing the past moves of the opponent.

On this particular project I would like to demonstrate my project to one of the leading

companies in the development sphere and continue refreshing my knowledge and

fulfill my experience in this sphere during my career life.

Summary of results

Requirements:

The main requirements of this project are design a working AI engine for the

prototype Dominoes 101 game. These requirements will provide me with a better

understanding of my project so that I can plan my project more efficiently. The end

user for this application would be Peter Smith, who will have a clear understanding of

my project.

Implementation: In this project I will use android studio tool, which will help me to design the layout

of the application in XML and add methods using the Java, which will interact with

each other to achieve the playable game. I will use the various classes, which will

help me solve a problem in the structured manor. For example the main classes will

enable me to position all the bones on the table, by crating two boards and other

classes will combined to surve the functionality for this game. The target users are

myself who will use this to improve the game and my supervisor.

Page 8: AI Dominoes Project

Page 8 of 42

Testing: Using an emulator with API 21 will do testing of this application; in order to test this

emulator should be preinstalled into the Android studio. I will use the built in

emulator to test my application against the bugs and make sure that it compiles

successfully in each phase.

Project Report: This report will allow me to document my project and make sure I have carried out

important steps that are required. Using this document I be able to understand my

application in future or make it easier for my client to understand if I end up selling

this application. The end user for this report is myself who will use this understand

this application and Peter Smith who will have a better understanding from reading

this report.

Page 9: AI Dominoes Project

Page 9 of 42

CHAPTER 2: LITERATURE REVIEW:

I have an advance understanding of business related subjects, however when it comes

to technical aspects specially the programming I have limited knowledge. As this

project is highly technical (covers both, programming and mathematical side) I have

to perform thorough research in order to understand how to program and use of

mathematics in programming. In order to understand this I have mainly used Internet

& books, below shows some of the recourses I have used:

To understanding the theory of game, use of AI (Artificial Intelligence) in game and

building aspects I start reading a book called “Developing game in Java”. (Brackeen).

This book has helped me learn about how game is designed with use of suitable GUI

(Graphical User Interface), AI (Artificial Intelligence) and mathematics using

probability. In this book I have mainly read following chapters:

• Chapter 3 interactivity and user interface – this chapter has helped me to

understand the necessary steps require in build a user-friendly interface. I will

use some of the techniques such as colour scheme and user interactive features

during implementation phase to build a simple user interface yet powerful

enough to direct users to a specific part in a game.

• Chapters 5 create 2D platform game- this chapter provides some great an

example of steps requires to build a 2D game. Once again I will use some of

these techniques such as implementation methods that can be used to build a

2D game such as onAction methods, onClick method etc… These methods

will help me to add basic functionalities needed for my game rather than

redesigning these methods. For example using OnClick method I will

implement a feature that will inform AI upon onClick action from user AI

should make its next move.

• Chapter 13 Artificial Intelligence- I found this chapter the most helpful

because it talks about how can I use mathematics to build a boat that can act

differently according to the input that users make. I will use this information

to construct a decision board for my game, which will use probability to make

appropriate decisions based on users moves.

Page 10: AI Dominoes Project

Page 10 of 42

In order to obtain a better understanding towards the programming I have explored

various websites. One in which I have found extremely helpful was Android

Developer website (Android). This website provides a step-by-step guide to build my

first Android app. After completing this tutorial I now had a clear understanding

towards programming such as the concept of methods, class etc… The context learnt

from this website will allow me during my implementation phase where I have to

write my own classes and methods to add the functionality requires to accomplish

objectives of this project.

When going through the tutorial from Android developer website (Android) I had several

questions about the UI (User Interface). In order to answer my questions I have used

UI section under Android development website (Android) to read about UI. This has

helped understand availability of various UI components in an android market that I

can use to make an application attractive, clear and user-friendly. I will use my

knowledge from this website and use it during my project to design dominos game UI

in such a way that is user friendly and simple for the end users to understand.

After having a basic understanding towards Android it’s was a time for me to find out

how an applications are built from scratch. This includes setting up android

environment, use of different libraries etc… In order to find out I have used YouTube (Thenewboston) to see how other people have build their android application(s) from the

scratch. After watching some of these vides I have decided to use Android Studio tool

to build my application, which has a built in emulator. Android Studio will first allow

me to program android application, test an application using built in emulator and the

IED is simple to use. During this video I have realized that the author was using many

classes, which were then linked with a master class. I will use similar technique as

this to build my application to, my app will consists of some of the classes like board,

dominos which will contain features that describes that specific class. For example a

class domino will have structure of domino.

Further in this project I had to make a use of grid to position the dominos, the grid

structure will allow me to easily calculate mathematics side of my project. The reason

for using grid is because the grid structure acts as a matrix to select/move dominos to

an appropriate box. To understand the grid system in Android I have followed a

Page 11: AI Dominoes Project

Page 11 of 42

simple tutorial (Rishabh) that explains the grid view in Android with a custom adaptor.

After completing this tutorial I manage to have a clear understanding of grid view that

gave me an idea of how would I go about and include mathematics (probability) in

my project. Having solved this problem will allow me to simplify my code by not

having to code all the possible next/current position of dominos.

3pages

Page 12: AI Dominoes Project

Page 12 of 42

CHAPTER 3: METHODS:

In order to successfully complete my project I will use waterfall methodology, the

model is consists of linear sequential flow as shown in diagram 1, advantages of

waterfall model is that the methodology provides developer the control over their

system, makes it easier for the end users/myself to understand and easy to manage.

These are important factors for my project because this project requires me to have a

full control over my system to make suitable changes to my project in order to desired

results. This methodology will also help me to manage my project because in my

project I will implement statistical known data, decision matrix, keeping track of

probability etc… All these can be confusing for the end users, however using

waterfall model I be able to mitigate this by keeping my project simple.

http://myanswerz.blogspot.co.uk/2012/12/waterfall-model.html

Page 13: AI Dominoes Project

Page 13 of 42

Requirements:

Main requirement of this project is to build a running Artificial Engine for the

prototype Dominoes game. In order to achieve error free application I had to compile

the application after inserting any new functions and updating the overall design of

the project. Requirements of my project can be split up to 2 part. Fisrt part is

requirement for the Game and how the methods interact with each other in order to

start and follow the sequence of activities in the game. Second part is requirement of

the AI engine describing how the functions such as getbestmove and updatethe

board(decision board with the values) cooperate and work in a bind to let the AI make

decisions.

Design:

In order to build my app I will use the principle of simple user interface suggested by

Android developers (REF). Android UI is built using “ViewGroup” and “View”

objects as you can see from the above diagram. viewGroup are invisible containers

that specified child node e.g. grid or vertical list, whereas view contains components

such as button, text box, text area, grid view (adaptors) etc… In this project I will use

grid view, which will allow me to display items in 2 dimensional scrolling grid

[http://codetheory.in/understanding-android-gridview/]. General approach of using

Page 14: AI Dominoes Project

Page 14 of 42

CustomAdapters is to help me to establish medium between code and the GUI for the

grid and player and their items. In my project I will have 5 viewGroups, each

containing several view objects. The view objects will contain buttons (to navigate

from one frame to another) and textboxes (to enter users name). Below shows 5

screens of my app (viewGroup) and the actions/components each screen holds (view).

Next I will guide you through the user journey from opening to terminating of my

application, the user journey will be represented in form of steps which will outline

actions can be performed within that step.

1. When a user unlocks his phone, the screen on

the left hand side will be presented to a user

(depending on a type of phone). In this screen we can

see that there are various icons (each represents an

application) that a user can select. My application

name will be “Dominoes Game” with a dominoes

icon. Upon clicking on Dominoes icon a user will be

directed to next screen as shown below:

1. This is the first screen of my application, at the top you I will have

welcome message to make sure a user have selected a right app.

2. In this textbox a user will have a privilege to add his/her name. This

will be shown during the game to make sure who is playing against

AI.

3. After entering your name, user need to click OK in order to progress

to the next screen.

1

2

3

1

Page 15: AI Dominoes Project

Page 15 of 42

1. The name entered from above screen will get

displayed here with your score.

2. This will display AI score so that you can have

a clear view of who is winning.

3. If a user don’t have a bone require to undertake

next action then he/she can click this button (Draw) to

obtain next randomly generated bone.

4. When you first start the game you will see 7

bones placed on the left hand side. In order to use

them a user can simply select a bone and click on

stage 5.

5. In this white space user will try outperforming

AI and AI will try outperforming a user by

using/placing a specific bone that can increase the

change of user/AI of winning. Finally, after the game

finished the score will be displayed in next screen as shown below:

1. This screen will be displayed if a user

wins.

2. This screen will be displayed if a user

losses.

1 23

4 5

1 2

Page 16: AI Dominoes Project

Page 16 of 42

Implementation (coding):

Creating layout of the project is kind of straight forward if you consume some time in

it, but thinking out of box to develop the methods and functions is the relatively

difficult part of the project. After watching numerous YouTube tutorials about the

Java programming language and following the guidelines shown in the materials

listed in the literature review, I have started thinking on the overall structure of classes

and linking the activities to each other to achieve the runnable AI player.

1. The overall structure and simpler classes where made first in this order:

Bone, Boneyard, Hand, Player, Board, then the AI class was made followed by the

StartGame class along with the rest of the classes (the custom adapters and resources).

All of these classes, custom adapters and resources are going to be explained in the

Results section of this report.

2. Layout of the application has been developed in the XML, which is built in to

Android Studio. (xml describes how to align and display various visual items).

(Similar to how CSS files work in web design. The files don't necessarily link to each

other since they must be set by the java code.

3. The AI is first invoked in the StartGame class and calls the AI's play function. His

hand and the board are compared using getAvailableMoves where a move is chosen

as described in the following pages. The AI updates his decision board every time he

draws (this is within the play function of the AI class) As well as when the player

plays (the update function is called from outside the AI class in this case).

Artificial Intelligence (AI):

The two biggest factors in strategy for playing dominoes are; determining your

opponent's tiles and identifying their weaknesses. Our AI attempts to do this by

implementing statistical known data and a decision matrix.

“A decision matrix is a list of values in rows and columns that allows an analyst to systematically identify, analyze, and rate the performance of relationships between sets of values and information. Elements of a decision matrix show decisions based on certain decision criteria. The matrix is useful for looking at large masses of decision factors and assessing each factor’s relative significance.”

Page 17: AI Dominoes Project

Page 17 of 42

http://en.wikipedia.org/wiki/Decision_matrix

In dominoes, our primary goal with the AI is to force the opponent to draw, we do this

by keeping track of probabilities of an opponent having any domino at any given

time. This is done using a matrix as such:

Let this be the graphical representation of decision board, the rows represent the first

dot value while the columns represent the second dot value. For example;

In getBestMove, the AI looks at his available moves and picks to play a domino with

the resulting open end dot value (call it x) having the largest possible x column value

in our summed decision board.

For example, in the above summed decision board, the AI will try to play a domino so

the resulting open end is of dot value “3” if it cannot, “4” and so on.

The Play function is where getBestMove is called and the function where the AI

actually makes a play. If the AI draws, updateBoardBone is also called since a new

Page 18: AI Dominoes Project

Page 18 of 42

known domino is introduced.

The function updateBoardBone updates this board given a domino. The domino given

can either be in our hand or something the player has just placed. It adds “10” to each

box in the rows of the first and second dot value of the given bone. It also sets the

given bone “box” to 60, saying that the player can no longer possibly have this

domino in their hand.

Decision Equation:

Where A is available moves represented by sequence J-k

(Available moves being resulting open end values)

D(A) returns the move with the highest (max) probability

(A move which the opponent most likely can not play on)

Pj represents the probability of the opponent have a domino with dotted value j

Pj=10k

Where k is the number of times the Ai has seen a domino with value j

( seen meaning a domino on the board or in the AI’s hand)

Testing In this project I will use unite testing method to test my system, unit testing is

application-testing approach, which tests certain part of my source code. In order to

perform unit testing I will use test cases which will explain the requirement I am

testing, test set up, the outcome I get and if test has passed or failed etc... I will write

test cases according to options I will have in each screen of an application.

Evaluation (maintenance): To be completed

Page 19: AI Dominoes Project

Page 19 of 42

CHAPTER 4: RESULTS:

Introduction:

In this chapter my aim is to present all my findings in each phase of waterfall model,

this chapter will have UML diagram (activity diagram) showing actions with in a

class, the actual look of dominos game (UI) and methods/java libraries I have used to

add certain functions.

Requirements:

As mentioned in the Method section, main goal of this strategy game is compiling

without errors, which is the job of classes to interact with each other in order to

provide overall functionality of this game. UML diagram (Activity diagram) below

shows the pattern of classes, actions within a class and dependencies.

Page 20: AI Dominoes Project

Page 20 of 42

Design:

Now I will design my UI using XML (Extensible Markup Language), the benefit of

using XML is that I will be able to keep the barrier between the UI and the behavior

of my app, this will provide me with the flexibility to edit my app look without having

disrupt its underlying functionalities. Screenshots below outlines app UI:

Home Screen:

This is a startup screen (might be different in other

phones); from this screen users have the privilege to

select dominoes application.

EnterTheNameScreen:

After clicking dominoes application a user will get

directed to this screen in which a user have the

privilege to enter his/her name and click ‘Ok’ in

order to proceed to the next screen. From the screen

you can see that I have provided a welcome

message upon first screen of this app, this is so that

it confirms that the user have opened a right app

from a list of apps.

Page 21: AI Dominoes Project

Page 21 of 42

Game Screen:

After clicking ok from “Enter The Name Screen” user will be navigated to the screen

on the left hand side. This is a default screen of a board; at the top of the screen we

have a user name/score and AI score. Bones on the left hand side of the screen gets

randomly generated and I have implemented a button on top called draw, upon

clicking this button a new bone will get added to the left side. The white screen in the

middle of the screen is where user can perform action(s). The screen on the right hand

sideshow if I perform first action the AI makes its best move.

Winning Screen:

Page 22: AI Dominoes Project

Page 22 of 42

After finish thing the game depending on who wins a specific screen will get

presented to a user. For example if a user wins then congratulation screen and user

score will be presented as shown on left hand side. If the user losses then a sorry

screen and score will be presented as shown on right hand side.

Implementation: Thisphaseissubdividedintothe3sections,whichareHomeScreen,EnterThe

Name and Game Screen. First two sections are short paragraphs representing

basic functionalities that the app provides, such as opening of the app and

enteringtheplayer’sname.HowevertheGameScreenisthecorescreen,which

is also subdivided into parts that explaining each class and their interaction

through out the game. All classes are going to be attached with the

correspondingpieceofcode,whichisgoingtobeexplainedinordertounderline

thebasicmethods,functionsandinstancesofclasses.

Home Screen:

ThisisthemenuofmybuiltinEmulator,inwhichuserscanselect“Dominoes“

among the various applications. However inmost cases the application is run

automaticallyassoonastheplayerunlocksthescreenintheemulator.

Enter The Name Screen:

In order to allow a player to enter his name I have created a class “Main Activity” - a

class that records a player name from input and passes it on to StartGame. (View is

changed at this point).

The above code is used to record a player’s name, line 22 created an instance name

Page 23: AI Dominoes Project

Page 23 of 42

called ‘intent’, which calls a StartGame class. In line 23-24 I am first creating a text

box and then it gets the inputted text and storing it into ‘intent’ instance as shown in

line 25.

Game Screen:

StartGame:I have used StartGame class to initialize: Board object, Player object and AI object. In

this class I will use onClick Listeners for the Hand, Grid and Draw.

Onclick Listener for Hand: when the user in the hand selects a domino, a variable

is set to the corresponding domino as shown in lines 59-60 in the code shown below:

OnClick Listener for Grid: If a domino was previously pressed in the hand (variable

is set) and if the move is valid, the move is made and the AI is invoked. If the hand is

empty after the move, the player wins (call to endgame function, which is going to be

explained further in this report sections). If the move is invalid, the hand domino

variable is reset.

Lines 89-90 are representing end game function if the hand of the player or AI is

empty else lines 91-92 invoke AI in case the hand is not empty yet.

Page 24: AI Dominoes Project

Page 24 of 42

Function invokeAI: Calls the play function in the AI class object. If the hand is

empty ( lines 125-126), AI wins (call to endgame). Otherwise the hand count is

updated and the app waits for user's next move. Lines 133-136 represent hand count

update for the AI.

Page 25: AI Dominoes Project

Page 25 of 42

OnClick Listener for Draw: If the Boneyard (deck) is non-empty as shown in line

109, then we draw and hand is updated. Adapter used in line 110 helps to maintain a

binding between code and GUI for the player and it’s items. Otherwise the move is

passed to AI, where AI keeps playing till we do not have the corresponding bone.

Finally tie can occur if neither player, nor does the AI have the correct bone to make a

move.

Function endgame: Code below is designed by creating Boolean “b” , which is to

determine if there is win, tie or loose. If our Boolean “b” is present , then player wins

and congratulation and the score messages are displayed(lines 148-152), else if the

score is set to 1000 as described in the “Invoke AI function” previously the tie

between the AI and player is established ( in lines 153-158). If neither of these are

true, then lines158-162 will be executed displaying the loose message along with the

score.

Page 26: AI Dominoes Project

Page 26 of 42

Function firstplay: Handles the first play automatically then passes on the turn to the

next player.

Code appearing above is the screen shot of the “firstplay” method; the purpose of this

method is to make the first move by AI or the human player automatically. Line 168

gets the heaviest bone (bone with the most dots) from the AI and line 69 gets the

heaviest bone (bone with the most dots) from the player. Line 174 I have used “if

statement” to check if the player and AI have/do not have the double bone (same

values on both side of the bone). If the condition is true I have used nested loop to

once again check if AI has the large double, if true then line 175 to 177 will get

executed (AI makes the move) else line 179-182 will get executed (player makes the

move). I have carried out similar steps mentioned above from line 189-204 to check if

“AI double but not played” then execute player else AI and “Player has heavier bone”

then execute player else AI.

BoardgBoard: A 2-Dim matrix representing the actual game board containing domino

objects. Code below shows the architecture of the G board, which is constructed using

9x14 matrix. This board is visible to the users to decide the position of their moves.

pBoard: A 2-Dim matrix representing all playable values in their respected locations.

Page 27: AI Dominoes Project

Page 27 of 42

This is one more board constructed to let the application decide which position is

available and to set the rotation of the bones as soon as the boundaries of the board

has been reached. Decision of availability of the positions will be maintained by the

numerous if statements.

gridB: An Arraylist used to translate our 2-Dim gBoard into a single dimension array.

GridB has been used to display the board with our custom grid layout adapter. Grid

layout custom adapter is therefore used to establish the binding between the code and

the GUI for the grid and it’s items.

Function PlaceDomino: Places the domino on the board in a legal manner.

Code below represents the legal manner of placing the dmino to the left. Righ, Top

and Bottom positions have been constructed in the same manner and called by the

enum position method at the end. All the possible areas where we can place a domino

are set by the pBoard, as it is the board containing the playable values.

Page 28: AI Dominoes Project

Page 28 of 42

100 value wich can seen from the code above in line 55 and 71 is the value given to

the positon of the bone in pBoard. Value 100 means the move can be made.

enum Position: . piece of code is constructed to call these entire if statements. Used to

indicate which side will be the joining side on the placed domino.

Function GetOpen: Gets all the playable values in pBoard, in sets of 3such as:

Value, x, y, value2, x2, y2.

Function GetPosition: Returns the relative position of the domino that will be played

on .Then I have made the same for other four positions(bottom, top, right). Lines

330-333 show if statement and the return activity which are integrated in order to

make it possible to return the left position.

Function GetPosition2: Returns which neighbors of the domino placed at x,y can

possibly be played on . This piece of code is followed by the same patterns for the rest

positions( top, bottom, right). Lines 361-365 are explaining Boolean expression

Page 29: AI Dominoes Project

Page 29 of 42

created in line 356 to identify which neighbor’s can be played on the placed domino

at (x,y).

BoneSimple object class representing a domino (left, right values and image ids). In line 19

I have used method called super which in charge of overriding the lines 20-23 as there

28 bones totally, depending on which we get. Lines 20-23 are there to set the structure

with the values of the bone. Lines 24-25 are representing the double bone, which has

the same amount of dots in each side of it.

Boneyard:Simple object class representing the deck (containing all the dominoes) .

Code below represents an Arraylist and random generator , which are used to hold the

bones and establish the random selection. Shuffling therefore is maintained as the

draw function in the startgame class, where application draws until the hand is full.

Page 30: AI Dominoes Project

Page 30 of 42

In lines 1516 as you can I see I have used the for loop to create a values for both sides

of the bone.

Code below is representing the availability of the bones in the Boneyard to let the

player to draw and contains remove bone method to remove the bone.

Hand:Object class representing the player (or AI's) hand

Function getHeaviestBone: Returns the "Heaviest Bone" in hand, the double with the

largest value or if none, the highest sum of dots on a domino

Page 31: AI Dominoes Project

Page 31 of 42

Function getAvailableMoves: Get the available open moves (where you can play &

what values), compares it with dominoes in hand and returns all possibilities of what

is playable.

Player:Simple Player object class Function play: If the play is legal. makes the play and

returns true. Otherwise, returns false as you can through lines 25-34.

Page 32: AI Dominoes Project

Page 32 of 42

AIdecisionBoard: a 2-Dim matrix where [x][y] represents the domino with dots x and

dots y. The value is the least probability of the opponent having the domino (60 =>

100% chance he doesn't have it). Following the sample of the code from the AI class

of the Dominoes app, you can see the 7x7 matrix was created in the line 10, for our

decision board. The functionality of the decision board for AI was explained in the

methods section of this report. Lines 22-26 are implemented, by using “for loops” to

construct and initialize the decision board for AI. As you can see 7 by 7 board was

created with “I” and “j” values, which represent two sets of values of dominoes.

Summed decision board developed through the codes in lines 31-42, are summing up

the probability of tiles , by letting the AI to choose the tile with the most probability

that opponent/player does not have the right tile to make the move.

Function Play: The AI determines the best possible move then makes the play, if no

moves available, the AI draws until there are or the deck is empty. Source of code

below outline the play function (in lines 45-55). Selecting the best possible move is a

different function , which is explained in the paragraph below.

Page 33: AI Dominoes Project

Page 33 of 42

Function getBestMove: the columns of the decisionBoard are summed and based on

the available moves, the AI chose a move such that the resulting open value “x” is the

largest possible value of the row “x” in the summed decision board. In other words,

the AI plays so that the player is least likely to have a domino with the resulting open

value. Lines 70-95 are showing cycles, storing open end values after the move and

loops through the summed board to figure out which tile is the most appropriate for

the AI to place( tile with the highest probability for player to have).

Function updateBoardBone: Updates the decisionBoard given a bone.This function

sets the value 60 to the board values of the left&right bone values and add the value

10 to the rows&columns of each bone value. . Initial knowledge about the each tile

the AI has , are the tiles which are already placed on the deck and the bones which AI

has got in his hand. Update the board method is setting all the probability values for

Page 34: AI Dominoes Project

Page 34 of 42

those bones which AI has seen already to 60 and sets the value 10 to the one, which

have not been seen.The value 60 therefore means that the opponent can not have that

particular tile.Code below(lines 98-119) demonstrates the sequence of the steps

carried out in order to achieve the update of the board method.

GridLayoutCustomAdapter

Medium between code and GUI for the grid and it's items.

ListLayoutCustomAdapter

Medium between code and GUI for the player's hand and it's items

Page 35: AI Dominoes Project

Page 35 of 42

Testing: My next step is to test my application in order to see if it’s functioning according to

my expectations. In order to achieve this I will write test cases for each sequence of

the code I written, as shown below:

Test No: 1 Objective: Run my emulator without any errors and my app should be included among other applications. Set Up:

1. Adil will click on run button in Android studio, which will load an emulator. 2. Adil will unlock the phone and click on application folder. 3. The application folder will consists of number of applications such as: Mail,

Gallery etc… 4. Among those applications I should be able to detect a Dominoes application.

Expected Results: 1. Emulator will run without any errors. 2. After emulator is on the screen, users will be able to interact with the mobile

screen. 3. User should be able to click on an application button, which should navigate

the user to list of other applications 4. User should be able to click on Dominoes application.

Test: 1. Emulator will open and allow users to interact. 2. Emulator have application a folder called “Applications” 3. Emulator will open list of applications. 4. Adil can now select Dominoes game and system should run that specific app.

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 2 Objective: Test that the application can allow a player to enter his/her name and allow him to interact with a button. Set Up:

1. A new user Adil will enter his name into the text box as ‘Adil’. 2. Adil will click ‘Ok’ button.

Expected Results: 1. The application will allow Adil to enter some text into a text box. 2. The application should allow Adil to click ok and move to next stage of the

Page 36: AI Dominoes Project

Page 36 of 42

game. Test:

1. The application will store Adil name in an instance, which will display in next screen.

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass See appendix E for the test cases from 3-8

Evaluation:

Objective of this project was to develop an Artificial Intelligence (AI) engine for the

strategically 2D table game Dominoes. Graphical interface within creating the grid

view for objects and setting the boards responsible for position of the tiles in the deck

were very time consuming. However, the biggest challenge I have faced was the

implementation of the AI engine, which ought to take real life decisions to block the

opponent and diminish the opponent’s chances to make the next move. Test cases

written by the help of emulator throughout the each section of the implementation

have helped to test the engines behaviors on every stage of the game.

PerformanceAs a result a successful functioning prototype of the game was developed. Matter of

luck and discrete calculations of AI engine have let the artificial player outperform

me. AI is showing good performance during the game and simultaneously takes into

the consideration the tiles locared on board and in his hand. Moreover AI is tracking

the players actions, such as if the human player is drawing the new tile and soon as

the player draws the AI get a new information about our hand. For example if there is

a chain of dominoes with three end values 3 ,4 and 5 , then AI is setting the value(60)

to all sides of the tiles with the same numbered dotted side.

It is only possible to decide if AI is making good/radical decisions after the game

ends, as then we can see which options he had and which ones he has chosen. From

the output of this project I can conclude that I have successfully met my overall

objectives, as the game is fully functional from both the player and AI side.

Page 37: AI Dominoes Project

Page 37 of 42

Conclusion:From chapter 1 to 4 I have successfully outlined the methods I have used to design

my game and the techniques undertook to implement this project. From my results I

can see that the method and implementation techniques have work well with my

problem domain. The application is making its best decisions over a human player;

this was all possible due to comprehensive planning and research. During the

implementation, the concept of OOP (Object Oriented Programming) has played a big

role by allowing me to easily set and get the objects, this avoids building of similar

objects in each class. Also the IED Android Studio has made the testing extremely

easy by having an built in emulator. This has avoided me pushing this application on

my phone in order to test it. The emulator has simulated a phone environment in

which I have tested my app. Integrating all these features/techniques have helped me

achieve my goal in designing the running AI engine for the Dominoes game.

FutureImprovements:Aspectsofthisprojectcanbesubdivedintofollowingsections:

GUI-Currently theGUI isdesignedusing2Dgraphics, this canbe improvedby

introducing3Dgraphicstomaketheinterfaceuserfriendly.3Dgraphicsinclude

3D textbox,switch game themes etc… Under GUI section I will also consider

adding background music (with the mute option available to user to select),

which will provide an entertaining environment and boost the players

motivation.

AI–IcanimproveAIbyintroducingsomecomplexbehaviorstotheAIsuch

analyzingthetimeittakesfortheplayertomakeitsnextmove.Iftheplayeris

takingmorethanestimatedtimetomakehisnextmove,thentheAIshouldknow

thattheplayerisfindingithardertoplay,asaresultAIshouldstartperforming

complexcalculationinordertoovercometheplayersstrategy.

Icanalsoallowplayertoselectdifferentgammingmode(easy,medium,hard),if

theplayerselectsaneasymodethentheAIshouldmakeasimpleprobability

calculationsandgetmorecomplexduringothermoredifficultmodes.

Finally I would like mention that Artificial Intelligence engines are the future of

technology and this project is a life example proving this philosophy.

Page 38: AI Dominoes Project

Page 38 of 42

Personalexperience:During this project I have realized that there are many mobile base games but

majorities of these games are simple (simple interactions between player and the

game). I personally believe that by introducing MAS (Multi Agent System) can

revolutionized the ways in which users can interact with their mobile games. If

anyone is seeking to design a game then I will advice them to use MAS which means

there are multiple agents who are trying to achieve same goals either by formulating

its decision making concept, controls or communications between agents. For a

problem domain like my I will have MAS who’s goal might be to find a best move

within the state space that can outperform a player, agent who finds the best path can

determine the next best move from AI. The best move can be represented as some

short of rewarding system so the agent with the highest reward within a second wins,

so the decision made by agent X can be the next best move in a game. This method

can also be used to improve my game because I can see it will enhance the

performance of my probability counts. So rather than calculating the best move

probability every time I can design MAS that can perform the calculation based on

the environment means according to each move a player move MAS will adapt to the

situations.

Page 39: AI Dominoes Project

Page 39 of 42

Works Cited [online]. at: ABNT_Author.XSL ABNT_Num_Alt.XSL ABNT_Num.XSL ACMCitSeq.XSL ACMNameSeq.XSL ACSCitSeq.xsl ACSCitSeq2.xsl AMA.XSL ASA.XSL CSECitSeq.XSL CSENameSeq.XSL HarvardAGPS.XSL HarvardAnglia.XSL HarvardExeter.XSL HarvardLeeds.XSL Humana.XSL IEEE_Alphabetical.XSL IEEE_Reference.XSL LNCS.XSL MHRAFootnote.XSL Nature.XSL types.xml Vancouver.XSL [online]. Last accessed 01 03 2015 at: https://developer.android.com/training/basics/firstapp/index.html [online]. at: https://developer.android.com/training/basics/firstapp/building-ui.html [online]. Last accessed 05 03 2015 at: http://istqbexamcertification.com/what-is-waterfall-model-advantages-disadvantages-and-when-to-use-it/ [online]. Last accessed 04 03 2015 at: http://web.stanford.edu/group/htgg/cgi-bin/drupal/sites/default/files2/zmiddleton_2002_1.pdf [online]. Last accessed 05 09 2014 at: http://codetheory.in/understanding-android-gridview/ [online]. Last accessed 01 09 2014 at: https://www.youtube.com/watch?v=tPFuVRbUTwA&list=PLFE2CE09D83EE3E28&index=17 Appendix E Test No: 3 Objective: Test that the application can show a stored name and load the Dominoes

Page 40: AI Dominoes Project

Page 40 of 42

interface. This includes randomly generated Dominos and space where a player can make his moves. Set Up:

1. A player sees his name “Adil” in top with score 0. 2. Adil can see some randomly generated Domenos on right hand side. 3. Adil can see white space where he can make his first move.

Expected Results:

1. Emulator will open a new UI 2. Dominoes will get generated automatically for the player to interact with. 3. Second Domino can be inserted in a playable area.

Test:

1. The application asks for a player’s name. 2. Application shows the names entered in the next screen 3. Application will generated random Dominos. 4. Application has a playable area (white box).

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 4 Objective: Test that the application can allow a user to make a move and record score. Set Up:

1. Adil selects his first dominoes 4/6 (dominoes with 4 dots on left and 6 dots on right hand side).

Expected Results: 1. Application will allow a player to select any Domino from the list and allow

the player to make a valid move (such as 5/4) into a playable area (white space).

2. Adil score will change to some number(s). 3. After a move from the player, AI will make immediate move. 4. AI score will change to some number(s)

Test: 1. Application have a list of Dominos for a user to select 2. Application allows valid move(s) by a user. 3. Adil score increases to 1 4. AI makes its next valid move(s) 5. AI score increase to 1

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 5 Objective: Test that the AI makes its move after a player.

Page 41: AI Dominoes Project

Page 41 of 42

Set Up: 1. Adil had the harvest bone therefore Adil makes his first move as 4/6 (first

move is automatically based on harvest bone) 2. AI thinks the next best move is 6/5 and makes its move.

Expected Results: 1. AI will use its decision board to check the next best move and makes the

move.

Test:

1. Adil makes his first move 2. Adil will wait 1second 3. AI made his move after Adil 4. The system will allow Adil to make his next move

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 6 Objective: Test if draw button is working (if I don’t have any moves then I can click draw button to get additional Dominoes) Set Up:

1. AI makes his sixth move as 6/5 2. Adil clicks draw button and Adil gets 2/4 Dominoes. 3. Adil again clicks draw button and this time he gets 6/2 bone, which can be use

against AI. Expected Results:

The application will randomly generate a bone when clicking Draw button Test:

1. Application generates a random bone for Adil and insert it in playable Dominos list.

2. Adil will use that Domino and makes his move and the application should accept that.

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 7 Objective: Test that the application allows player or AI to win Set Up:

1. Adil only have 6/2 bone 2. Game finishes with congratulation message with Adil score against AI score. 3. Adil closes the game window

Expected Results:

1. System should take Adil to new screen.

Page 42: AI Dominoes Project

Page 42 of 42

2. System should display a message.

Test: 1. Soon as Adil runs out of Dominoes the application will show a new screen.

Application will print Congratulation message if Adil wins and Sorry message if AI wins.

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass Test No: 8 Objective: Test that the application displays some message and score. Set Up:

1. Adil makes his last move 6/2 2. Adil don’t have any bones to play 3. Adil wins and closes the application.

Expected Results:

1. A message will show depending on who won the game (if a player winds the congratulation message else sorry message).

2. With the message the game score will be displayed. 3. Adil should be able to close the application.

Test:

1. Application display congratulation text if a player wins 2. Application display sorry message is a player losses. 3. Application closes

Test Recorded: Not recorded Date: 15/04/2015 Tester: Adil Gaimov Result: Pass