I wrote this game to practice some simple OOP. You play against the computer, but be aware that the computer has no real AI, as it just generates its moves randomly. The loser is the one whose turn it is when there is only one match left in the stack.
import java.util.Random;
import java.util.Scanner;
class Game {
private boolean gameOver;
Scanner input;
Player computer, human;
public Game() {
computer = new Computer();
human = new Human();
input = new Scanner(System.in);
}
public void runGame(){
System.out.println("Welcome to the game of Nim! How many matches would you like to play with?");
human.setMatchesLeft(input.nextInt());
while (!gameOver){
if (computer.getMatchesLeft() != 1){
System.out.print("Computers move: ");
computer.playerTurn();
computer.printStatus();
if (computer.getMatchesLeft() == 1) {
gameOver = true;
System.out.println("Human loses, computer wins.");
}
}
if (human.getMatchesLeft() != 1){
System.out.print("Humans move: ");
human.playerTurn();
human.printStatus();
if (human.getMatchesLeft() == 1) {
gameOver = true;
System.out.println("Computer loses, human wins.");
}
}
}
}
}
abstract class Player {
private static int matchesLeft;
public abstract void playerTurn();
public abstract void printStatus();
public void setMatchesLeft(int x){
matchesLeft = x;
}
public int getMatchesLeft(){
return matchesLeft;
}
}
class Human extends Player {
private int humanTurn;
private Scanner input;
public Human(){
input = new Scanner(System.in);
}
public void playerTurn(){
humanTurn = input.nextInt();
while ( humanTurn > (getMatchesLeft() / 2) || humanTurn < 1 ) {
System.out.print("Illegal move. Please pick at least 1 matches.\n");
humanTurn = input.nextInt();
}
setMatchesLeft(getMatchesLeft() - humanTurn);
}
public void printStatus(){
System.out.println("Human removes " + humanTurn + " matches. " + getMatchesLeft() + " matches left. ");
}
}
class Computer extends Player {
private int computerTurn;
Random computerGen;
public Computer(){
computerGen = new Random();
}
public void playerTurn(){
computerTurn = computerGen.nextInt(((getMatchesLeft() / 2) - 1) + 1) + 1;
setMatchesLeft(getMatchesLeft() - computerTurn);
}
public void printStatus(){
System.out.println(computerTurn);
System.out.println("Computer removes " + computerTurn + " matches. " + getMatchesLeft() + " matches left. ");
}
}
public class Nm {
public static void main (String[] args){
Game newgame = new Game();
newgame.runGame();
}
}