Best way to code my unintelligent Nim game? - java

This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}

First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...

Related

How can I start the program over again

I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}

Multiplayer Random Number Guessing Game: How to create random number for each player? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am creating a random number generator multiplayer game (LAN).
I need help on how to create a code to make each player receive their own random number, and whenever one player guesses a code, the next turn would be a new player. Similar to where the output would show the following,
Fred, Please Guess the random number (integers only!!): 5
TOO LOW
Tom, Please Guess the random number (integers only!!): 95
TOO HIGH
John, Please Guess the random number (integers only!!): 50
TOO LOW
Then when a player guesses correctly, their turn is skipped and the game will end when all players have guessed their numbers, showing the number to guesses each person had, as well as the numbers they guessed previously.
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Integer> guessedNumbers = new ArrayList();
int x = 0;
int players = 0;
System.out.println("how many players are there?:");
players = checkint(players);
int arraySize = guessedNumbers.size();
int[] numPlayers = new int [players];
boolean play = true;
boolean validGuess = true;
String [] pNames = new String[players];
for (int i = 0; i<players; i++) {
System.out.println("New player, what is your name?:");
pNames[i] = keyboard.nextLine();
}
while(play) {
int randNum = myRand.nextInt(100) + 1;
int numOfGuesses = 0;
do {
System.out.println("Enter what you think the number is between 0 and 100!:");
x= checkint(x);
guessedNumbers.add(x);
if (x < 0) {
System.out.println("we don't accept negative numbers");
if (x > 100) {
System.out.println("that number is above the random number generator range");
}
}
numOfGuesses++;
if (x == randNum) {
System.out.println("that's correct!");
System.out.println("It took you " + numOfGuesses + " tries!");
System.out.print("these are all the numbers you guessed:");
for(int count=0; count<guessedNumbers.size(); count++){
System.out.print(guessedNumbers.get(count) + ",");}
System.out.println("");
boolean playError = true;
//if ("Yes".equals(answer)) {
do {
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0) {
play = true;
playError = false;
} else if (answer.compareToIgnoreCase("no") == 0) {
play =false;
playError = false;
System.out.println("Thank you for playing");
} else {
//you messed up
System.out.println("You answer was invalid");
playError = true;
}
} while (playError == true);
}
else if
(x>randNum)
System.out.println("Lower than that!");
else if
(x<randNum)
System.out.println("Higher than that!");
} while (x != randNum);
}}
}
static int checkint(int a) {
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
String enteredString = "";
do {
try {
enteredString = myScanner.next(); //Read into a string
enteredNumber = Integer.parseInt(enteredString.trim()); //then cast as a integer
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e) {
System.out.println("Your entry: \"" + enteredString + "\" is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError == true ); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
You are doing simple things in a complex way, however, my code can still be replaced by a compressed version but you can understand this better. Following code is doing exactly what you want it to do. I've:
Created Player class, so each player will keep record of guessedNumbers, Number of Guesses and it's name.
You don't have to make tons of variables like pName[], play, validGuesses etc...
I have changed some of the If-Conditions and removed the outer while-loop
Added new round concept, so whenever a player guessed the number, the number got changed.
and much more ....
UPDATED Code: Now each Player has a different random number to guess.
import java.util.*;
public class GuessNumber
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Player> players = new ArrayList<Player>();
int x = 0;
System.out.println("how many players are there?:");
int noPlayer = checkint();
boolean validGuess = true , playError = true;
for (int i = 0; i<noPlayer; i++)
{
System.out.println("New player, what is your name?:");
players.add(new Player (keyboard.nextLine()));
}
for (int i = 0; i<noPlayer; i++)
{
players.get(i).number = myRand.nextInt(100) + 1;
}
int i =0; // for chossing different player each time
do
{
System.out.printf(players.get(i).name + " enter what you think the number is between 0 and 100!: ");
x= checkint();
players.get(i).guessedNumbers.add(x);
players.get(i).numOfGuesses++;
if (x == players.get(i).number)
{
System.out.println("That's correct!");
System.out.println("It took you " + players.get(i).numOfGuesses + " tries!");
System.out.print("These are all the numbers you guessed: ");
System.out.println(players.get(i).guessedNumbers);
do
{
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0)
{
playError = false;
players.get(i).number = myRand.nextInt(100) + 1; // creates a new random number for second round of the game
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
}
else if (answer.compareToIgnoreCase("no") == 0)
{
playError = false;
System.out.println("Thank you for playing");
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
players.remove(i);
}
else
{
System.out.println("You answer was invalid");
playError = true;
}
} while (playError);
}
else if (x>players.get(i).number)
System.out.println("Lower than that!");
else if (x<players.get(i).number)
System.out.println("Higher than that!");
if(i == noPlayer-1 || !(playError))
i = 0;
else
i++;
}while (players.size() > 0);
System.out.println("\n\n******************** Every Body Guessed Their Numbers ******************");
}
static int checkint()
{
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
do
{
try
{
enteredNumber = Integer.parseInt(myScanner.next().trim());
if (enteredNumber < 0 || enteredNumber > 100)
{
System.out.println("Either you entered a negative number or number is above the random number generator range");
numberError = true;
}
else
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e)
{
System.out.println("Your entry is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
// now each player would have its own record.
class Player
{
int numOfGuesses= 0;
ArrayList<Integer> guessedNumbers = new ArrayList<Integer>();
String name = "";
int number = 0;
public Player(String nam)
{
name = nam;
}
}
NOTE: I've added some new lines to output on the screen , once a players wins and want to play again or not. I recommend you to compare your code with mine, so that you'll get a better understanding of your approach vs mine. Do let me know if you find something difficult to understand.
Just use the Random class:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
I referenced here.
How do I generate random integers within a specific range in Java?

Having trouble w/ returning and passing values; "counting"

Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}

Rock paper scissors, play again?

For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;

Nim game - specify winner

import java.util.Scanner;
/**
*#author Andy
*#verison 21.11.2012
*/
public class NimGame
{
public static void main (String[] args)
{
System.out.println ("********** Hello Welcome to the game Nim *********");
System.out.println (" The game is relatively simple.... ");
System.out.println (" This is a game for two players. ");
System.out.println (" There is a heap containing 10 to 20 stones.");
System.out.println (" Players take turns to remove 1-4 stones ");
System.out.println (" The player who removes the last stone wins. ");
System.out.println ("******************************************************************");
Scanner scan = new Scanner (System.in);
int heapSize = 15;
int stones = 0;
boolean nextInteger = false;
boolean lessThanFour = false;
String player1 = "Player 1";
String player2 = "Player 2";
String player = player1;
System.out.println ("The number of stones currently in the heap is :- " + heapSize);
System.out.println();
while (heapSize > 0)
{
nextInteger = false;
lessThanFour = false;
System.out.println (player + ":" + "how many stones will you take from the heap?");
System.out.println();
while (nextInteger == false && lessThanFour == false)
{
if (scan.hasNextInt())
{
nextInteger = true;
stones = scan.nextInt();
if (stones <=4 && stones >0)
{
System.out.println();
System.out.println ("You picked " + stones);
heapSize = (heapSize - stones);
if (heapSize >= 0)
{
System.out.println();
System.out.println ("There are " + heapSize + "stones left");
System.out.println();
lessThanFour = true;
System.out.println();
if (player.equals(player1))
{
player = player2;
}
else
{
player = player1;
}
}
else
{
System.out.println ("Bad input, please try again");
nextInteger = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input, please try again");
scan.nextLine();
}
}
}
}
}
}
I dunno how to implement a way to specify player 1 or player 2 being the winner once the sizeheap (number of stones left) reaches 0. Any help would be appreciated. Also when the sizeheap reaches a negative number, it will display 'bad input' but then any other number inserted after that also displays 'bad input.'
Thanks!
Basically, you just need to rewrite if (heapSize >= 0) so it displays a win message:
if (heapSize > 0) {...} else { ...win... }
Here's the critical part, fixed, streamlined a bit, and edited:
if (stones <= 4 && stones > 0) {
System.out.println ("\nYou picked " + stones);
heapSize = (heapSize - stones);
if (heapSize > 0) {
System.out.println ("\nThere are " + heapSize + " stones left\n\n");
// Could use a ternary operator here:
// player = (player.equals(player1) ? player2 : player1);
if (player.equals(player1)) {
player = player2;
}
else {
player = player1;
}
}
else {
if (player.equals(player1)) {
System.out.println("Player 1 wins!");
}
else {
System.out.println("Player 2 wins!");
}
}
}
Further tips:
You can just use a newline \n instead of an System.out.println().
The lessThanFour flag is probably unnecessary

Categories

Resources