My friend tried asking this question earlier and wasn't specific enough, so I'll try being a bit more detailed. We're trying to make a basketball simulator between two players that keeps playing until one player has reached 21 points, and then stops. We got fairly far, and while the program runs, it continues executing, instead of ending at 21 points for one player, and keeps running until I believe the program crashes. Does anyone have any idea on what needs to be added to prevent the program from executing after 21 points for one of the two players? I will post the code below, and if you would like a screenshot of the output, I would be happy to provide one. Thank you!
Code:
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.Random;
public class KobeVsLebron {
//VARIABLES
public Random randomGenerator;
private static int kscore = 0;
private static int lscore = 0;
//declare scanner
static Scanner input = new Scanner(System.in);
//main method
public static void main(String[] arguments) {
System.out.println("\n Welcome to Kobe vs Lebron Simulation");
System.out.println("In this simulation you will have a choice to flip a coin.");
System.out.println("Whatever the outcome of the flip is the starting players ball.");
System.out.println("The simulation is based off of a long standing argument");
System.out.println(" Kobe Bryant vs Lebron James in a game of 21.");
MainMenu();
}
/*******************************************************************************/
METHODS
//Main Menu
//PlayKobe
//PlayLebron
//LeaderBoard();
//ReadFile();
//WriteFile();
//Win();
private static void MainMenu(){
char choice;
do {
System.out.println("\nTo the run the simulation flip the coin by choosing 'F', \nTo print the leaderboard enter 'L' \nTo quit enter 'Q'");
choice = input.next().charAt(0);
switch (choice) {
case 'F':
case 'f':
FlipCoin();
break;
case 'L':
case 'l':
// LeaderBoard();
break;
case 'Q':
case 'q':
default:
System.out.println("Invalid Choice! TRY AGAIN!");
}
}
while (choice != 'Q');
}
private static void FlipCoin() {
Random randomGenerator;
int sides;
int currentsides;
System.out.printf("\nThe coin will be flipped heads(Kobe) or tails(Lebron)");
randomGenerator = new Random(); //initialize random object
sides = 2; //default number of sides
currentsides = randomGenerator.nextInt(sides)+1; //initialize roll (1-2)
System.out.printf("\nThe coin is being flipped.....");
//TIME DELAY '1000 is one second'
try {
Thread.sleep(1500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
if(currentsides == 1 ){
System.out.printf("\nThe coin has been flipped to heads. \nKobe has the ball.");
PlayKobe();
}
if(currentsides == 2){
System.out.printf("\nThe coin has been flipped to tails. \nLebron has the ball.");
PlayLebron();
}
}
private static void PlayKobe() {
Random randomGenerator;
int shot;
//int kscore = 0;
int shotclock;
if(kscore < 22){
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nKobe drives in to the basket");
System.out.printf("\nLebron on his tail!");
System.out.printf("\nKobe scores the lay-up! and thats two for Kobe! ");
kscore += 2;
PlayLebron();
}
if(shotclock == 2){
System.out.printf("\nKobe dribbles towards the line ");
System.out.printf("\nLebron has him covered, Kobe takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Kobe!");
kscore += 3;
PlayLebron();
}
if(shotclock == 3){
System.out.printf("\nKobe is locked down and shaking!");
System.out.printf("\nLebron Steals the ball! ");
PlayLebron();
}
}
private static void PlayLebron(){
Random randomGenerator;
int shot;
// int lscore = 0;
int shotclock;
if(lscore < 22){
System.out.printf("\nLerbon has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nLebron drives in to the basket");
System.out.printf("\nKobe on his tail!");
System.out.printf("\nLebron scores the lay-up! and thats two for Lebron!");
lscore += 2;
PlayKobe();
}
if(shotclock == 2){
System.out.printf("\nLebron dribbles towards the line ");
System.out.printf("\nKobe has him covered, Lebron takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Lebron!");
lscore += 3;
PlayKobe();
}
if(shotclock == 3){
System.out.printf("\nLebron is locked down and shaking!");
System.out.printf("\nKobe Steals the ball! ");
PlayKobe();
}
}
}
Currently you have
if(kscore < 22) {
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
Which essentially means your code does nothing besides printing when a player reaches the score limit, you want to add a return statement to go back to your main loop.
You'll also want to check for when the score exceeds 21 and not the opposite.
if(kscore > 21) {
System.out.printf("\nKobe has won the game of 21!");
return;
}
You'll need that for both players ofc.
Related
The goal of the game is to use a while loop. In this loop, it will determine who wins the game based on the number entered. The numbers are from 1 to 20. Challenge is the variable set at 10. If <= Challenge, playerOne loses one point. If > challenge, the monster loses a point. Whoever loses 3 points first loses the game. I do not need to have random number generation, I just need inputs via the scanner function.
I thought variables were necessary for the scanner, which is why I added the Dice variables. They are not used and I am confused if I need them or not to make the scanner work so that the user can make inputs.
I am also confused on how to subtrack from the player and monster when they get hit. Which is why I set the variables under each block for the amount of points they have. This is wrong but I am stuck as to how to properly display this.
I was able to get some messages to display, but any number would give me the same result which was -1 for player one.
Essentially I am stuck on how to write this in code from here. Any help is greatly appreciated.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(20);
}
public static void task3(int challenge) {
challenge = 10;
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your dice roll");
int diceRollOne = sc.nextInt();
while (player <= challenge) {
System.out.println("Monster misses");
System.out.println("Enter your dice roll");
int diceRollTwo = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 2;
System.out.println("Enter your dice roll");
int diceRollThree = sc.nextInt();
} else if (player > challenge) {
System.out.println("-1 for monster");
monster = 2;
System.out.println("Enter your dice roll");
int diceRollFour = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 1;
System.out.println("Enter your dice roll");
int diceRollFive = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 1;
System.out.println("Enter your dice roll");
int diceRollSix = sc.nextInt();
continue;
} else if (player <= challenge) {
System.out.println("-1 for player");
player = 0;
System.out.println("Monster Wins");
int diceRollSeven = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 0;
System.out.println("Player wins!");
int diceRollEight = sc.nextInt();
}
}
}
}
}
}
}
When you are writing a while-loop, you must first think about the condition of when will the loop terminate / when will the loop continue. In your case, you want the loop to end when either player or monster become 0. Therefore the condition for the while-loop to continue running is the opposite, i.e. both of them > 0.
Then think about what do you want to do in each iteration. In your case, the repetitive tasks are
Read an integer from user input
compare the integer with challenge
subtract 1 point from the corresponding variable
Finally, after the loop ended, you can use the value of player and monster to determine the result and print it out.
import java.util.Scanner;
public class Task3 {
public static void main(String args[]) {
task3(10);
}
public static void task3(int challenge)
{
int player = 3;
int monster = 3;
int dice = 0;
Scanner sc = new Scanner(System.in);
while(player > 0 && monster > 0)
{
System.out.println("Enter your dice roll");
dice = sc.nextInt();
if(dice > challenge)
{
monster--;
}
else
{
player--;
}
}
if(player > monster)
{
System.out.println("Player wins!");
}
else
{
System.out.println("Monster wins!");
}
}
}
P.S. Try to understand the code instead of just copy and paste to your homework :)
You dont need to have a seperate variable to get each input from the scanner.
You can get the input each time in the while loop and compare the value to challenge.
we will exit the loop only when player or monster becomes zero.
once outside the loop, you can check who won and print the result accordingly.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(10);
}
public static void task3(int challenge) {
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
int diceRoll;
while (player == 0 || monster == 0) {
System.out.println("Enter your dice roll");
diceRoll = sc.nextInt();
if(player < challenge)
player--;
else
monster--;
}
if(player < monster)
System.out.println("Player wins!");
else
System.out.println("Monster Wins");
}
}
if you want only numbers between 1 and 20 as the input, you should also add an if condition which checks this after getting the input
So I'm writing some code for a card game and within this card game I have coded how the first round works. My question is how I would be able to repeat this code over and over again until the cards run out( since each card can only be used once). I'm thinking that I have to use a while loop. For convenience I will explain what each of the methods here do so that you may understand, so please bear with me. Some of this is useless code that I haven't gotten to complete yet and make useful.3
The rules to the game : https://tobakumokushirokukaiji.fandom.com/wiki/E_Card
** Here are the methods : **
typeOfCard(); - this tells you which side you are playing on and is decided randomly, so far you can only play on the Emperor side.
winOrLose() - this is the last method i worked on before making this post, this is what I am trying to implement to allow me to replace the current win or loss output as strings which i can call easier than print statements. I want to make this so that the games which are won can set the int wincounter to 1 so it can print this out.
emperorsTurn() - this is the method that asks the main questions of which card you would like to play versus the computer.
wincounter() - some code i need to delete so dont worry about this
import java.util.Random;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args) {
int numberOfCards = 7;
if (numberOfCards > 6) {
numberOfCards--;
//System.out.println("your number of cards is " +numberOfCards);
}
typeOfCard();
}
public static void typeOfCard() {
Random card = new Random();
int number = 0;
for (int counter =1; counter <=3;counter++){
number = 1+card.nextInt(2); }
if (number == 1) {
System.out.println("your are playing on the emperor side");
}
if (number ==2){
System.out.println("You are playing on the slave side ");
}
if (number ==1){
emperorsTurn();
}
}
public static void winOrLose(){
int wincounter = 0;
String win = "You won the round";
String lose = "You lose the round ";
if (wincounter >0) {
System.out.println(win);
}
else if (wincounter == 0) {
System.out.print(lose);
}
}
public static void emperorsTurn() {
Random cards = new Random();
int computerinput = 0;
for (int counter = 1; counter <= 3; counter++) {
computerinput = 1 + cards.nextInt(2);
}
Scanner sc = new Scanner(System.in);
System.out.println("Please pick the card you are playing. \n if you are playing the Emperor press 1, if you are playing the citizen press 2 ");
int userinput = sc.nextInt();
if (userinput == 1 && computerinput == 1) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
}
else if (userinput ==1 && computerinput ==2) {
System.out.println("you have played the emperor the emperor defeats the citizen");
winOrLose();
wincounter();
}
else if (userinput == 2) { //when the user input is 2
if (computerinput == 1) {
System.out.println("you have played the citizen, this defeats the slave");
wincounter();
} else if (computerinput == 2) {
System.out.println("you have played the citizen, this ties with the citizen");
}
//print out something else if number is not 1,2 or 3
}
}
public static void wincounter() {
int i = 0;
if (i < 1)i++;
System.out.println("you have won " +i +" number of draws");
}
}
Try doing a while loop that compares the number of cards left to the minimum number needed to play a game.
while (numberOfCards > minNumberNeeded) {
playGame();
}
Write a program to simulate a coin toss. First, ask the user to "call" or predict the toss. Next, let the user know you are tossing the coin. Then report whether the user was correct.
Example:
Please call the coin toss (h or t): h
Tossing...
The coin came up heads. You win!
This is about what I am supposed to do. This is the code I have so far:
package inClassCh4Sec8to9;
import java.util.Random;
import java.util.Scanner;
public class ClassCh4Sec8to9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter you guess (1 for heads, 0 for tails, 2 to quit):");
int call = input.nextInt();
int heads = 1;
int quit = 2;
int tails = 0;
if (call == quit) {
break;
} else if (call == heads) {
} else if (call == tails) {
} else {
System.out.println("invalid");
continue;
}
Random random = new Random();
int coinflip = random.nextInt(2);
if(call == coinflip){
System.out.println("Correct!");
}else{
System.out.println("Sorry, incorrect.");
}
}
}
}
My problems:
I can get a random number no problem but it allows the h and t to be used as 1 and 0.
I want h or heads to equal 1 as an input.
Instead of Random.nextInt(), I would prefer nextBoolean(). Don't redeclare your Random in a loop. If the input starts with an h set a guess to true; otherwise, make sure it is valid (and set it false). Then flip the coin, and compare the result. Something like,
Scanner input = new Scanner(System.in);
Random random = new Random();
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine().toLowerCase();
boolean guess = call.startsWith("h"), coin = random.nextBoolean();
if (call.startsWith("q")) {
break;
} else if (!guess && !call.startsWith("t")) {
System.out.println("invalid");
continue;
}
if ((guess && coin) || (!guess && !coin)) {
System.out.printf("The coin came up %s. You win!%n", coin ? "heads" : "tails");
} else {
System.out.printf("The coin came up %s. You lose!%n", coin ? "heads" : "tails");
}
}
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine();
String heads = "h";
String tails = "t";
if(call==null || call.length() > 1){
break;
}
System.out.println("Tossing...");
int random=(int)(Math.random()*2);
if(random<1){ //assume that, if random variable is smaller than 1 then it is head. If bigger than 1 and smaller than 2, then tails.
if(heads.equals(call)){
System.out.println("The coin came up heads. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}else{
if(tails.equals(call)){
System.out.println("The coin came up tails. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}
}
}
}
Prompt: "Write a program to play the pig game against the computer. At each turn, the current player will
roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your
opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player
rolls a 1, all the points accumulated for that round are forfeited and the control of the dice
moves to the other player. If the player rolls two 1s in one turn, the player loses all the points
accumulated thus far are forfeited and the control moves to the other player. The player may
voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll
again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the
other player to win. Computer is going to flip a coin to choose the first player "
My problem: I got the program to output that either the computer or the player is going first based on a coin flip. However, how would I actually prompt the program to run a method of the person chosen to start first, and then how would I switch between the computer and player at the end of each turn? Btw, I know this code is incomplete, but I hope that my question makes sense.
Code so far:
import java.util.*;
public class NavaiPigGame
{
public static final int POINT = 30;
public static final int FORFEIT_POINTS = 20;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
play(rand,input);
}
// desription of game
public static void description()
{
System.out.println("***********************************************************************************");
System.out.println("Write a program to play the pig game against the computer. At each turn, the current player will");
System.out.println("roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your");
System.out.println("opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player");
System.out.println("rolls a 1, all the points accumulated for that round are forfeited and the control of the dice");
System.out.println("moves to the other player. If the player rolls two 1s in one turn, the player loses all the points");
System.out.println("accumulated thus far are forfeited and the control moves to the other player. The player may");
System.out.println("voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll");
System.out.println("again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the");
System.out.println("other player to win. Computer is going to flip a coin to choose the first player");
System.out.println("***********************************************************************************");
System.out.println("lets start the fun");
}
//flips a coin and decides who starts the game
public static String flipCoin(Random rand)
{
int coin = rand.nextInt(2);
String comp = "";
switch (coin)
{
case 0: comp = "heads";
break;
case 1: comp = "tails";
break;
}
return comp;
}
public static int rollDice(Random rand)
{
int dice1 = rand.nextInt(6)+1;
int dice2 = rand.nextInt(6)+1;
System.out.println("Dice 1: " +dice1);
System.out.println("Dice 2: " +dice2);
return dice1+dice2;
}
// select a random name of the computer via arrays
public static String nameComputer(Random rand)
{
int name = rand.nextInt(10);
String compName = "";
switch (name)
{
case 0: compName = "Lisa";
break;
case 1: compName = "Kathy";
break;
case 2: compName = "Hali";
break;
case 3: compName = "Jack";
break;
case 4: compName = "Alex";
break;
case 5: compName = "Max";
break;
case 6: compName = "Jill";
break;
case 7: compName = "James";
break;
case 8: compName = "Martha";
break;
case 9: compName = "Lauren";
break;
}
return compName;
}
public static void play(Random rand, Scanner input)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
boolean gameOver = false
boolean turnOver = false
description();
String compName = nameComputer(rand);
System.out.println("Hi my name is " + compName);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hi " + name + ", I am flipping the coin to determine who goes first");
System.out.print("press any key to start the game. ");
input.nextLine();
String flip = flipCoin(rand);
int turn;
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
}
}
}
Create :
A playTurn(int turn) function (1 for the player, 0 for the computer) that handle a play turn (roll dice, calculate point etc.)
A boolean function that check wether there is a winner or not. Example : isWinner(int player) (again, 1 for the player, 0 for the computer)
Use the function a first time in your if() else statment like that :
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
playTurn(turn);
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
playTurn(turn);
}
Then you can add :
do {
if(turn == 1){
turn = 0;
playTurn(turn);
}else{
turn == 1;
playTurn(turn);
}
while ( !isWinner(1)|| !isWinner(0) );
This is not very well designed, but it should hopefully give you a hint on what to do next.
I am attempting to write a program that helps a user make the correct EV play for each hand. However at the minute I am using card value (i.e. total of two cards) to base my decisions. For example 9=9, 10=10, j=11, q=12.... I would like the use to be able to enter in their actualy hands e.g. Adks (ace of diamonds, king of spades). This would be more accurate as it would take into account the suited value of the hand etc. Can anyone give me advice on the best way to incorporate this? Many thanks in advance! My cuurent code is below!
package uk.ac.qub.lectures;
//importing resources (scanner)
import java.util.Scanner;
public class PokeGame {
public static final int MIN_POSITION = 1;
public static final int MAX_POSITION = 8;
public static void main(String[] args) {
// declaring user position
int userPosition = 0;
// setting up scanner
Scanner scanner = new Scanner(System.in);
// integer referring to use again or not
int useAgain = 0;
// boolean getting valid input for repeat
boolean repeat = false;
// declaring number value of each card
int cards;
do {
// getting user position
do {
System.out.printf("Please enter position between %d and %d\n",MIN_POSITION, MAX_POSITION);
userPosition = scanner.nextInt();
} while ((userPosition < MIN_POSITION) || (userPosition > MAX_POSITION));
// getting hand hand strength
System.out.println("Enter card value");
cards = scanner.nextInt();
switch (userPosition) {
case 1:
case 2:
if (cards > 10) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 3:
case 4:
case 5:
if (cards > 13) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 6:
case 7:
case 8:
if (cards > 17) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
default:
System.out.println("ENTER VALID POSITION");
}
do {
System.out.println("Do you advice on another Hand?");
System.out.println("Enter 1 for Yes, Enter 0 for No");
useAgain = scanner.nextInt();
if ((useAgain == 1) || (useAgain == 0)) {
repeat = false;
} else {
System.out.println("Invalid Input, please enter 1 or 0");
repeat = true;
}
} while (repeat);
} while (useAgain != 0);
// clean up resources
scanner.close();
}// method end
}// class end
If you take the card input like this; "AA", "9T" or "9Ts", you can then compute a hand value based on suitedness and gaps like such using you input cards:
import java.util.Arrays;
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String[] hand = (scanner.nextLine() + 'u').toUpperCase().split("");
String values = " 23456789TJQKA";
int[] cards = new int[] {values.indexOf(hand[1]), values.indexOf(hand[2])};
Arrays.sort(cards);
int gap = cards[1] - cards[0] - 1;
boolean pair = gap == -1;
boolean suited = hand[3].equals("S");
char[] cards = new char[] {(char)values.charAt(cards[0]), (char)values.charAt(cards[1])};
int handValue = 0;
// adjust value based on pairs, suitedness or connectedness
if (pair) // hand is a pair
handValue += 10; //or whatever you want
else if (suited) // hand is suited
handValue += 3; //or whatever you want
if (gap == 0) // hand is no gap
handValue += 5; //or whatever you want.
if (gap == 1) // hand is one gap
handValue += 3; //or whatever you want.
if (cards[1] == 'A' && cards[0] == 'K' && suited) // AK suited
System.out.println("AK Suited!");
else if (cards[1] == 'A' && suited) // Ax suited
System.out.println("Ax Suited!");