Let’s make an from scratch 🌟. android machine learning game Are you fascinated by ? Do you like ? Do you want to make a ? machine learning Java or Android cool project using android and machine learning If yes, then you’re certainly at the right place. Here we will be making an android application which uses machine learning to the user. defeat Yes, defeat!! That means as you play along, it will become more and more pro at the game and your techniques, so you better prepare to lose. But even after losing, you’ll definitely be proud. Why, you ask? Well, learn, and you made it pro in the game. So, who’s the boss? you made it For starting purposes, let’s start with a simple game, with less possibilities. I think something like, will do just fine. Rock, Paper and Scissors This post will help you understand how you can make a game with , so you can make an amazing project game of your own, after this! machine learning and android Let’s dive into understanding how our app will progress, in a simple flow chart. Android App → Gives options for Rock/Paper/Scissor → User chooses one of them → If first time, then a random choice by computer → Otherwise, computer analyses the user input, and uses statistics to choose the one with more probability to win → Game continues, computer becomes more pro. So this is our app in a flow chart, which will give us direction, when we are stuck at what to do now. Simple Developer Tip: Always make a simple flow chart before making an app, to guide your journey during it’s making. Now let’s dive into some code. Start a new project on or IDE of your choice. Head toward the . We will start with the code, first. Android Studio MainActivity.java file Java Let’s first initialise some variables and flags. So add the following code for that in your . MainActivity /*first two are for previous result second two are for recent result*results[0][x][0][x] 0 at index 0 or 2 is a win*results[1][x][1][x] 1 at index 0 or 2 is a tie*results[2][x][2][x] 2 at index 0 or 2 is a loss*results[x][0][x][0] 0 at index 1 or 3 is for rock*results[x][1][x][1] 1 at index 1 or 3 is for scissors*results[x][2][x][2] 2 at index 1 or 3 is for paper*/ private int[][][][][][] results6D = new int[3][3][3][3][3][3];private int[][][][] results4D = new int[3][3][3][3];private int[][] results2D = new int [3][3]; private int lastResult =- 1;private int lastCompMove =- 1; private int secondResult =- 1;private int secondCompMove =- 1; private int status = 0; I have commented in the code for more understanding. We will be using last and recent choices by the user to train our . Machine Learning model Now we should add the code that gives user the choice to . Also the code which shows what the computer drew, and the result of the game. choose from Rock, Paper and Scissor The code like this would do for the above discussed aspect of our game, also this is the code inside the method of our code. userMove(view) int userMoveInt; Button b = (Button) v;String name = b.getText().toString(); switch (name) {case ("Rock"): {userMoveInt = 0;break;}case ("Paper"): {userMoveInt = 1;break;}default:userMoveInt = 2;} int compMoveInt;String compMoveStr;int resultStatus;compMoveInt = nextCompMove(); if (compMoveInt == 0)compMoveStr = "rock"; else if (compMoveInt == 1)compMoveStr = "paper"; else if (compMoveInt == 2)compMoveStr = "scissors"; elsecompMoveStr = "nothing"; String text = "I drew "+compMoveStr+", ";resultStatus = checkResult(compMoveInt,userMoveInt); if (resultStatus == 0)text+="You Win!"; else if (resultStatus == 1)text += "It's a Tie."; else if (resultStatus == 2)text += "You Lose!"; TextView output = findViewById(R.id. );output.setText(text);trainModel(resultStatus,compMoveInt); output float[] percentages = analyzeResults();int[] changes = changes(percentages);int rockChance = changes[0];int paperChance = changes[1]; text = "Rock: "+String. (rockChance)+"%"; valueOf ((TextView) findViewById(R.id. )).setText(text);text = "Paper: "+String. (paperChance)+"%"; rPer valueOf ((TextView) findViewById(R.id. )).setText(text);text = "Scissors: "+String. (100-rockChance-paperChance)+"%"; pPer valueOf ((TextView) findViewById(R.id. )).setText(text); sPer int top = Math. (rockChance,Math. (paperChance,100-rockChance-paperChance));text = "Confidence\n"+String. (Math. (2*(top-50)))+"%"; max max valueOf round ((TextView) findViewById(R.id. )).setText(text); confidence Also we are using integer . 0 for rock, 1 for paper and 2 for scissors Now let’s write some code for the and . Also, this code is inside the method of our code. computer to choose learn from the user nextCompMove() if (lastResult == -1) // that's default for the paperreturn 1; int chanceOneHundred = (int)(Math. ()*99)+1;float[] percentages = analyzeResults();int[] changes = changes(percentages);int rockChance = changes[0];int paperChance = changes[1];int compMove; random if (chanceOneHundred < rockChance)compMove = 0; else if (chanceOneHundred<rockChance+paperChance)compMove = 1; elsecompMove = 2; return compMove; If you understand a bit of probability, then you know, choosing any one of rock, paper or scissors at random has probability . 1/3 or ~33% So, we are putting the default chances for every choice, as 33%. The code to , for the method looks something like this: change the choices changes(percentage) int totalPercentages = (int) (percentages[0]+percentages[1]+percentages[2]);int rockChance = 33;int paperChance = 33; if (totalPercentages != 0) {rockChance= (int) (100*percentages[0]/totalPercentages);paperChance= (int) (100*percentages[1]/totalPercentages);} return new int[]{rockChance, paperChance}; Now let’s , and choose something that has the most probability to win the game for the computer. help computer analyse the moves of the user That will be our code for the method : analyzeResults() float[] percentages=new float[3];if (lastResult == -1)return percentages; int\[\]\[\] relevantResults; //noinspection ConstantConditions if (lastResult!=-1) { int\[\]\[\] resultsTo2D; int\[\]\[\] results4DTo2D = results4D\[lastResult\]\[lastCompMove\]; if (secondResult!=-1) { int\[\]\[\] results6DTo2D=results6D\[secondResult\]\[secondCompMove\]\[lastResult\]\[lastCompMove\]; resultsTo2D = _totalAmount_(results6DTo2D)<_totalAmount_(results4DTo2D)&&_totalAmount_(results6DTo2D)<9?results4DTo2D:results6DTo2D; } else resultsTo2D = results4DTo2D; relevantResults = _totalAmount_(resultsTo2D)<_totalAmount_(results2D)&&_totalAmount_(resultsTo2D)<1?results2D:resultsTo2D; } else relevantResults = results2D; for (int i=0;i<percentages.length;i++) { // percentages[i]=1+(relevantResults[2][i]*4+relevantResults[1][i]-relevantResults[0][1]*2);percentages[i]=1+(relevantResults[2][i]+relevantResults[0][i 0?2:i-1])*4;if (percentages[i] < 0)percentages[i]=0;}return percentages; 2?0:i+1])*4-(relevantResults[0][i]+relevantResults[2][i Take some time to understand this code, which is almost . If you understand this, you almost understand the whole code for the game. self explanatory Let’s also complete the code, so we’re done with the of the game. trainModel(resultStatus, compMove) machine learning crux part if (lastResult != -1) {results4D[lastResult][lastCompMove][resultStatus][compMoveInt]++; if (secondResult != -1) results6D\[secondResult\]\[secondCompMove\]\[lastResult\]\[lastCompMove\]\[resultStatus\]\[compMoveInt\]++; secondResult=lastResult; secondCompMove=lastCompMove; } results2D[resultStatus][compMoveInt]++;lastResult=resultStatus;lastCompMove=compMoveInt; And you’re all done. You’ve made yourself a machine learning android game, which almost against the user. certainly wins But, wait! ? We certainly don’t want to leave the user in dark, about who won the game, now do we? Where’s the winning part So, let’s write the code for which tells the user, about the winning or losing of the game. checkResult(compMove, userMove) /*Status 0 is a win*Status 1 is a tie*Status 2 is a loss*/int resultStatus;if (compMoveInt == 0 && userMoveInt == 1 || compMoveInt == 1 && userMoveInt == 2 || compMoveInt == 2 && userMoveInt == 0) {resultStatus = 0;TextView wins= findViewById(R.id. );int winAmount=Integer. (wins.getText().toString());wins.setText(String. (winAmount+1));}else if (compMoveInt == userMoveInt) {resultStatus = 1;TextView ties = findViewById(R.id. );int tieAmount = Integer. (ties.getText().toString());ties.setText(String. (tieAmount+1));}else {resultStatus = 2;TextView losses = findViewById(R.id. );int lossAmount = Integer. (losses.getText().toString());losses.setText(String. (lossAmount+1));} wins parseInt valueOf ties parseInt valueOf losses parseInt valueOf return resultStatus; And yes, now you’ve coded yourself everything you need for your machine learning android game to work and defeat anyone. The UI and some other fine tweaking in the code, can be found on my . GitHub repository . The full source code for the app You’re all done now, for sure. What are you waiting for? Go show your friends how . pathetically they can lose to your android game Go and Show Off ! Read my previous post about making a simple animated and clean website easily.