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
Related
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");
}
}
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;
}
...
Im trying to make a rock, paper, scissors game where you choose 1,2 or 3 for rock then displays what you've chosen and what the computer has chosen. I then need to keep track of score for wins and at the end of every round ask the user if they want to play again.
import java.util.Scanner;
public class Rock5
{
//-----------------------------------------------------------------
// Plays the Rock-Paper-Scissors game with the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int OPTIONS = 3;
final int ROCK = 1, PAPER = 2, SCISSORS = 3;
final int COMPUTER = 1, PLAYER = 2, TIE = 3;
int computer, player, winner = 0;
int wins = 0, losses = 0, ties = 0;
String again;
Scanner in = new Scanner(System.in);
do
{
computer = (int) (Math.random() * OPTIONS) + 1;
System.out.println();
System.out.print ("Enter your choice - 1 for Rock, 2 for " +
"Paper, and 3 for Scissors: ");
player = in.nextInt();
System.out.print ("My choice was ");
// Determine the winner
switch (computer)
{
case ROCK:
System.out.println ("Rock.");
if (player == SCISSORS)
winner = COMPUTER;
else
if (player == PAPER)
winner = PLAYER;
else
winner = TIE;
break;
case PAPER:
System.out.println ("Paper.");
if (player == ROCK)
winner = COMPUTER;
else
if (player == SCISSORS)
winner = PLAYER;
else
winner = TIE;
break;
case SCISSORS:
System.out.println ("Scissors.");
if (player == PAPER)
winner = COMPUTER;
else
if (player == ROCK)
winner = PLAYER;
else
winner = TIE;
}
// Print results and increment appropriate counter
if (winner == COMPUTER)
{
System.out.println ("I win!");
losses++;
}
else
if (winner == PLAYER)
{
System.out.println ("You win!");
wins++;
}
else
{
System.out.println ("We tied!");
ties++;
}
System.out.println();
System.out.print ("Play again (y/n)?: ");
again = in.nextLine();
}
while (again.equalsIgnoreCase ("y"));
// Print final results
System.out.println();
System.out.println ("You won " + wins + " times.");
System.out.println ("You lost " + losses + " times.");
System.out.println ("We tied " + ties + " times.");
}
}
Use
player = Integer.valueOf(in.nextLine());
Instead of
player = in.nextInt();
and it'll work, because if not, the number you enter goes into player, and the \n characater goes into again = in.nextLine() and because it's different of y it stops.
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;
/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}