Skip to content

The Nim Game – MIT App Inventor Tutorials

Nim is a mathematical strategy game which two players take turn to remove any number from different piles. There are many variations of the game, in this tutorial, there will be three piles with number three, four and five respectively. The winner is the player who takes the last number.

UI Components:
Label, Horizontal Arrangement, Button, Notifier


Start Game

Create three variables to keep track of the number in different piles and also a variable to keep track the player’s turn. This below example, updateButton procedure is created to update the text of all three buttons when any of the number changes. When RestartGameButton is clicked, reset the variables and UI.

Button Click

When user clicked any of the three buttons, we will use Notifier text dialog to ask for the number user will be taking away from the selected button. After user input a number, we will need to check for several invalid input conditions:

  1. Input number should be less than remaining number on the button
  2. input number should not be less than zero

If input is valid, we will then check for the winning condition. If the sum of all three piles is zero, then the player wins the game.

Above example shows only the logic for Button1, the same logic needs to be done for Button2 and Button3. If the winning condition is not met, update the isPlayerOne variable. We will also change the UI to indicate different player’s turn.

Complete Program

Other Resources