I am coding a pig game in Java, and I need help adding up the score. The game's goal is to roll two dice, and the values of those two dice are added together, and the player who gets to 100 first wins. I want to loop the values (which I called "Added") so that it continuously adds up by themselves.
Thank you in advance
By the way, I'm hardly done most of the game, so mind the gaps, lol.
import java.util.Random;
import java.util.Scanner;
public class Pig {
static int player, Continue, roll1, roll2;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
Random r2 = new Random();
System.out.print("Enter 1 to play against computer\nEnter 2 to play against another person\n");
player = keyboard.nextInt();
if (player == 1) {
System.out.println("\nPlaying against the computer...");
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added = roll1 + roll2;
System.out.println("\nYour total is " + added);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
if (Continue == 1) {
do {
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added2 = roll1 + roll2;
int added3 = added + added2;
added = added2;
added2 = added3;
System.out.println("\nYour total is " + added3);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
} while (Continue == 1);
}
} else {
System.out.print("Bye");
}
/*if (player == 2){
System.out.println("Playing against another person...");
}
else {
System.out.print("Bye");
count++;
*/
}
}
Related
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
So i'm still a beginner but I managed to get this code but it didn't work like I wanted, my main problem is that every time I press 1 it resets the enemy instead of keeping the same one. I would really appreciate if someone could help me. So far I have only made writing 1 do something.
package Game;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to Dragon Heart");
System.out.println("1. Start");
System.out.println("2. Quit");
int input = 0, enemyhealth = 75, enemyattack = 15, playerhealth = 100, playerattack, random;
boolean enemydead = true, playerdead = false;
input = in.nextInt();
if (input == 1) {
System.out.println("Game started!");
while (0 != 1) {
if (enemydead = true) {
enemyhealth = r.nextInt(50) + 51;
enemyattack = r.nextInt(15) + 6;
System.out.println("An enemy appears, it has " + enemyhealth + " health points and " + enemyattack + " attack points");
} else {
System.out.println("The enemy now has " + enemyhealth + "health points");
}
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println("3. Run away");
System.out.println("4. Do nothing");
input = in.nextInt();
if (input == 1) {
playerattack = r.nextInt(5) + 21;
random = r.nextInt(2) + 1;
enemyhealth = enemyhealth - playerattack;
if (random == 1) {
playerhealth = playerhealth - enemyattack;
}
if (enemyhealth <= 0) {
enemydead = true;
System.out.println("The enemy has been killed");
} else {
enemydead = false;
}
}
}
} else if (input == 2) {
System.out.println("Game quit.");
}
}
}
Your logic for defense away is dubious, but your problem is here:
if(enemydead = true)
You're reassigning enemydead to true every single time.
You really want to check if the enemy is dead, which is accomplished with this:
if(enemydead)
Further, you could clean up while (0 != 1) to be while(true) instead. However, you're going to need to include a break statement somewhere in that loop so that it's not an infinite loop like it is now.
Lastly, it's a good idea to have lower-case package names as opposed to upper-case package names.
So I made quite a few changes to my code and now it complies, but I get the wrong totals and it always thinks Player 2 wins, even before it hits "20". For some reason it isn't reading player 1 totalScore until after player 2 has rolled and then it does not calc player 2 turnTotal. When I made changes before, one thing would start working, but another would stop, so I took it back to where I began to have problems once it would compile.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore += dice;
System.out.print("Player 1 turn total is " + turnScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
{
totalScore += turnScore;
}
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
{ do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 += dice2;
System.out.print("Player 2 total is " +turnScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r") && dice != 1); {
totalScore2 += turnScore2;
}
}
if(totalScore2 >= WIN);
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
}
}
}
There is an error in the loop for player2/computer's turn. It's in the first if-else loop, located in the else portion.
input keyboard.nextLine();
should be
input = keyboard.nextLine();
It works fine after correcting that error.
Also, pay close attention to the compilation errors, they will point you towards which lines are generating said error.
Revision:
I think this works the way you intended it to.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore = dice; //removed +=??? think it's only the value of dice roll?
//either way it's used to compute total, which would be redundant if not
totalScore +=turnScore; //added to compute totalScore before turn is over
System.out.print("Player 1 turn total is " + totalScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore); //previously total wasn't computed
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}while(input.equalsIgnoreCase("r"));
//totalScore += turnScore; was removed + curly braces that seemed to attach it to the above while loop
//it isn't needed due to totalScore now being calculated after dice is rolled when !=1(else portion)
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
break; //added to break the loop if player 1 wins
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 = dice2; //removed += ... same as for player 1's turn
totalScore2 += turnScore2; //added totalScore2 calculations.
System.out.print("Player 2 total is " +totalScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r")); //{ <- incorrect brace + fixed loop for dice2 !=1, then removed it :P since you already did a check inside the do-while loop
//totalScore2 += turnScore2; removed, no longer is needed
//}
//} <- not needed nor is the brace that was infront of the do while loop.
if(totalScore2 >= WIN) //removed semicolon since it ended the if statement before it's body
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
if(totalScore>totalScore2) //added loops to check which score is higher and terminate
{
System.out.println("Player 1 Wins!");
break;
}else if(totalScore==totalScore2){
System.out.println("It's a Tie!");
break;
}else if(totalScore<totalScore2){
System.out.println("Player 2 Wins!");
break;
}
}
}
}
I also recommend installing an IDE such as Netbeans or Eclipse. An IDE would make your life much easier, especially with formatting and syntax errors.
I'm completely new to coding and I was wondering if you guys can help me. This is part of a code in which you battle a vampire, RPG style. My program does not loop back to my characters turn after I set the turn number to one near the bottom of the code, why is this?
/**
* Created by f on 7/30/2014.
*/
import java.util.Scanner;
import java.util.Random;
public class rpgBattle {
public static void main(String[] args) {
// Declarations
int charHp = 3941;
int enemyHp = 5200;
String charName;
int numDmg;
int dmgMultiplier = 1;
String playerInputSt;
int playerInput;
int turn = 1;
int miss;
//Processes
Scanner user_input = new Scanner(System.in);
System.out.println("Enter your name.");
charName = user_input.next();
System.out.println();
System.out.println("A vampire emerged!");
do {
System.out.println();
System.out.println(charName + "'s HP: " + charHp + "/3941");
System.out.println("The Vampire's HP: " + enemyHp + "/5200");
System.out.println("What will you do?");
System.out.println("Enter the number corresponding to the action you would like to perform.");
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println(turn);
playerInputSt = user_input.next();
playerInput = Integer.parseInt(playerInputSt);
if (playerInput == 1) {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println("The Vampire protected itself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(100) + 550;
}
enemyHp = enemyHp - numDmg / 1;
System.out.println();
System.out.println(charName + " attacks!");
System.out.println("The Vampire took " + numDmg / dmgMultiplier + " damage!");
turn = 2;
} else if (playerInput == 2) {
System.out.println();
System.out.println(charName + " guards");
System.out.println(charName + " recovered 394 HP!");
charHp = charHp + 394;
dmgMultiplier = 2;
turn = 2;
};
} while (charHp > 0 && enemyHp > 0 && turn !=2);
do {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println(charName + " braced himself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(500) + 200;
charHp = charHp - numDmg / dmgMultiplier;
}
System.out.println("The Vampire attacks!");
System.out.println(charName + " took " + numDmg / dmgMultiplier + " damage!");
dmgMultiplier = 1;
turn = 1;
} while (turn == 2);
}
}
It will never end because in the top level loop, the condition to get out is that the character's health drops below 0. However, you are never decreasing his HP. You are only decreasing the vampire's HP, but not the character. If you want the game to end, make the vampire attack the character too. That way, in some point his HP will drop below 0 and the game will end.
However, to make it more realistic, you should make the game end when the HP of the vampire OR the character are 0, and not when both of them are below 0. To achieve that, instead of using 3 loops, use 2, but changing the condition so that when either one of them has no HP, it will end:
do {
do {
...
} while (turn == 1);
} while (charHp > 0 && enemyHp > 0);
Without spending too much time analyzing all of your code, it looks like you have nested a Do..While Loop for charHp and a Do..While Loop for enemyHp. I think you need only one Do..While Loop that loops until either charHp or enemyHp is zero.
do {
do {
//.... Lots of code removed for brevity in the answer .....
} while (turn == 1);
} while ((enemyHp > 0) && (charHp > 0));
or should it be like this, with only one Do..While Loop
do {
//.... Lots of code removed for brevity in the answer .....
} while ((turn == 1) && (enemyHp > 0) && (charHp > 0));
What is the purpose of the variable turn ? Once a valid value is entered its value will be 2 untill the end of the game so the inner while will always loop only once.
But the the code will still be executed each time as the outer loops continue to loop until a score drops to 0.
If you want to know the number of turns you are playing, you should increase turn:
turn++;
and remove the most inner while loop.
If you want to loop until the user has entered a valid value, you should initialise turn at the beginning of the most inner loop:
turn=1;
good luck.
So this is my code now:
public class PigTry2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Variables
int start;
int total;
//Methods
Scanner quest = new Scanner (System.in);
die1 x = new die1 ();
die2 z = new die2 ();
// Game
System.out.println("Hello. Would you like to play PIG? 1 for yes");
start = quest.nextInt();
if (start == 1){
x.roll();
z.roll();
System.out.println("You roll: "+ z.getEyes() + " " + x.getEyes());
do {
System.out.println("Would you like to roll again");
start = quest.nextInt();
if (start == 1)
x.roll();
z.roll();
System.out.println("You roll: "+ z.getEyes() + " " + x.getEyes());
} while(z.getEyes() != 1 && x.getEyes() != 1);
total =
}
}
}
I have tried a few different methods, and I want to add up the total sum of the rolls that happen. I simply can't figure out how to do this. Anyone able to help me out?
If I understand what you want, I'd suggest this:
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Variables
int start;
int total = 0;
//Methods
Scanner quest = new Scanner (System.in);
die1 x = new die1 ();
die2 z = new die2 ();
// Game
System.out.println("Hello. Would you like to play PIG? 1 for yes");
start = quest.nextInt();
if (start == 1){
x.roll();
z.roll();
total += 2; //You just rolled twice, so lets increment by 2
System.out.println("You roll: "+ z.getEyes() + " " + x.getEyes());
do {
System.out.println("Would you like to roll again");
start = quest.nextInt();
if (start == 1)
x.roll();
z.roll();
total += 2; //EDIT: Rolled again, so ingrement by 2 again
System.out.println("You roll: "+ z.getEyes() + " " + x.getEyes());
} while(z.getEyes() != 1 && x.getEyes() != 1);
System.out.println("Total amount of rolls: " + total);
}
}
Something else: Users won't be able to cancel rolling until they throw a "1", because the if-statement in the do-while-loop won't quit the loop. You could use a flag to indicate, whether the user want's to keep rolling:
boolean finished = false;
do {
System.out.println("Would you like to roll again");
start = quest.nextInt();
if (start == 1) {
x.roll();
z.roll();
total += 2; //EDIT: Rolled again, so ingrement by 2 again
System.out.println("You roll: "+ z.getEyes() + " " + x.getEyes());
} else {
finished = true;
}
} while(z.getEyes() != 1 && x.getEyes() != 1 && !finished);