My java game isn't working - java

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.

Related

Java. Need assistance with adding up the numbers for pig game

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++;
*/
}
}

Resetting a game to start over in java

I created a dice game between the user and computer that loops 10 rounds - but if one of the game rounds is a tie - then it will ask if you want to play again and restart the game. I'm having a problem with the last part as the game iterates over at random times now. Any suggestions?
import java.util.Random;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("User vs. Computer Dice Game");
boolean Correct = false;
boolean Replay = false;
while(Replay == true) {
}
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for(int i =1; i<11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6)+1;
System.out.println("User rolled: "+usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6)+1;
System.out.println("Computer rolled: "+computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if(usernum == computernum) {
System.out.println("It\'s a tie!");
System.out.println("Do you want to play again? (Y/N) ");
System.out.println();
if (a.equalsIgnoreCase("N")){
Replay = true;
}
else {
Correct = false;
}
}
}
}
System.out.println();
}
}
}
Some notes:
You never set Correct=true.
Once inside the "while (Correct==false)" loop, you never test Replay.
There is no point in creating rand2. Just reuse rand1.
You have "for (int i=1;i<11;i++)" for the main loop.
Inside of that loop, and it's a tie, you ask if you want to play again, but there is nothing there to end the loop, so the inner for loop will continue to play out until you hit 11.
You might add a break statement when it's a tie to abort the for loop.
In fact, you're probably better off just aborting the loop and then asking the question again at the top of the while loop:
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for (int i = 1; i < 11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6) + 1;
System.out.println("User rolled: " + usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6) + 1;
System.out.println("Computer rolled: " + computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}
if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if (usernum == computernum) {
System.out.println("It's a tie!");
// Exit early from the for loop:
break;
}
}
}
else
{
Correct = true;
}
}

How do I start a different method over after another Method has finished in java?

I'm making a gambling game. The player enters a bet amount. After that a die is rolled three times, then based on the value of the die rolls, 1 of 4 things happen. Then you get to start again with the new Pot amount. I cant figure out how to start it again. I tried putting the method name i want to start at the end of the last method in the sequence and it kinda of works. It starts but when i put in a bet amount it doesnt do anything.
Here is my code
import java.util.Scanner;
public class Game {
private double Bet;
private double Pot = 50;
// private double TotalPot;
private int[] die = new int[3];
public Game() {
Pot = 50;
Bet = 0;
}
public void introText() {
System.out.println(
"Welcome to game Bet an amount.\nIf all of the three die together is greater than 12, \nyou get to keep your bet, if you roll doubles you win \ndouble your bet, if you roll triples you win triple \nyour bet. If your roll meets non of this criteria you lose your bet.A bet of 0 \nends the game.");
}
public void inputBet() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your bet: ");
Bet = keyboard.nextDouble();
if (Bet > Pot) {
System.out.println(
"Error, Bet out of range. Please enter a bet amount that is lower or the same as the current Pot. ");
inputBet();
} else if (Bet == 0) {
System.out.println("Thank you for playing. You end the game with a pot of " + Pot);
System.exit(1);
} else if (Bet < 0) {
System.out.println("Error,");
inputBet();
}
}
public void removeBet() {
Pot = Pot - Bet;
}
public void rollDie() {
Die bob = new Die();
int total = 0;
for (int i = 0; i < 3; i++) {
die[i] = bob.rollDie();
System.out.println("Your die number is listed below");
bob.displayDie(die[i]);
total = total + die[i];
}
bob.displayDie(total);
}
public void displayingDie() {
System.out.println("Pot amount before dice rolls $" + Pot);
}
public void dieComparison1() {
if ((die[1] == die[2]) && (die[0] == die[2])) {
Pot = (Bet * 3) + Pot;
System.out.println(+Pot + "if theyre all equal");
} else if ((die[0] == die[1]) || (die[0] == die[2]) || (die[1] == die[2])) {
Pot = (Bet * 2) + Pot;
System.out.println(" Congradulations! You win double your bet.");
} else if (die[0] + die[1] + die[2] > 12) {
Pot = Pot + Bet;
System.out.println("You win. But only your bet amount back");
} else if (die[0] + die[1] + die[2] < 12) {
// Pot = Pot - Bet;
System.out.println("Sorry You lose you bet amount");
}
}
public void print() {
System.out.println("The current Pot amount is: " + Pot);
inputBet();
}
}
You have a conception problem. You should not control your execution flow nor do io actions from your Game class. This is mainly a problem of separation of concerns. Each method of this class should only do actions relative to gambling. For exemple inputBet must only change bet and do controls, in fact it must only be a setter and be renamed setBet and throws IllegalArgumentException for exemple.
You can then do something like this in your main :
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Game game = new Game();
while(true){
Double bet = keyboard.nextDouble();
if(bet == 0){
//main loop break case
break;
}
try{
game.setBet(bet);
}catch(IllegalArguementException excpt){
system.out.println("error " + excpt.getMessage());
// skip next steps and do new loop iteration
continue;
}
// rest of execution flow
game.rollDice();
game.displayDice();
game.compareDice();
game.print();
}
System.exit(0);
}
and the setBet method could be :
public void setBet(Double bet){
// Range controls
if (bet > Pot || bet < 0) {
Throw new IllegalArgumentException("Bet out of range. Please enter a bet amount that is lower or the same as the current Pot. ");
}
this.bet = bet;
}

A "Stick Game" program in Java not working correctly?

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();

Guessing Game, with a While loop

i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.

Categories