Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

creating a number game, help with how to switch players

$
0
0
The game is for 2 players you start with 7 to 21 coins and each player has to take away 1, 2, or 3 coins, whoever gets the count to 0 wins. I'm having trouble on how to switch the players and assigned which one to go first...

here is the class:
public class Nim
{
	//instance data
	private int nCoins = 21;
	private int player =  1;

	//----------------------------------------------
	//Constructor -- initializes nCoins and player
	//----------------------------------------------

	public Nim(int coins, int starter)
	{
		if (coins >=7 && coins <=21)
			this.nCoins = coins;
		else
			System.out.println("Invalid input, 21 coins is assigned to your game.");
			
		if(starter == 1 || starter ==2)
			this.player = starter;
		else
			System.out.println("Invalid input, player 1 is assigned to be the first.");
	}



	//----------------------------------------------
	//Removes coins from the row.
	//----------------------------------------------

	public void takeCoins(int remove)
	{
		if (remove <= nCoins)
			nCoins = nCoins - remove;
		else
			System.out.println("You can only remove " + nCoins + " From the row");
	}



	//----------------------------------------------
	// Display the game status.
	//----------------------------------------------
	public void gameStatus()
	{
		System.out.println("Number of coins left: " + nCoins);
		System.out.println();
		System.out.print("Player" + player + ", ");
	}

	//----------------------------------------------
	// Returns nCoins.
	//----------------------------------------------

	public int getCoins()
	{
		return nCoins ;
	}

	//----------------------------------------------
	// Returns player.
	//----------------------------------------------

	public int getPlayer(){

		return player;
	}

}




here is the main:

import java.util.Scanner;

public class TestNim
{
	public static void main(String[] args)
	{
		Scanner scan = new Scanner(System.in);

		System.out.println("Who goes first, player 1 or 2?");
		int player = scan.nextInt();


		System.out.println("how many coins do you want to play, choose a number in the range of 7 to 21");
		int coins = scan.nextInt();

		Nim nimGame = new Nim(coins, player);

		while(nimGame.getCoins()>0)
		{
			nimGame.gameStatus();

			System.out.println("how many coins would you like to take, 1, 2, or 3?");

			int take = scan.nextInt();
			nimGame.takeCoins(take);
		}

		System.out.println("Game over!");
		System.out.println("Game won by: " + nimGame.getPlayer());


	}
}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>