So i am working on a school project and the project is to make a simplified yahtzee program with two of the yahtzee point systems, ex small ladder or three of a kind and so far i have made small ladder (1,2,3,4,5) and big ladder (2,3,4,5,6) to work but i have 2 questions.
1. How can i make a point system for three of a kind?
2. A part of the project is to make a category if you dont get one of the implied point systems, ex if you get (1,1,4,5,6) then the user is gonna get the option to choose which number he wants to pick for maximum points. I know i cant explain this very well since im swedish and my english isnt the best. But here is my code:
import javax.swing.*;
import java.util.*;
public class Projekt1 {
public static void main(String[] args) {
char fortsatta = 'j';
boolean ja;
do{
JOptionPane.showMessageDialog(null, "Välkommen till Johans Yatzy");
int starta = JOptionPane.showConfirmDialog(null, "Vill du starta spelet?", "Spela igen",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(starta == JOptionPane.YES_OPTION ){
JOptionPane.showMessageDialog(null, "Du har nu startat spelet");
int[] tar = new int[5];
for(int i=0; i<5; i++){
tar[i] = (int)(Math.random()*6+1);
}
String output = "";
java.util.Arrays.sort(tar);
for (int i = 0; i < tar.length; i++) {
output = output + tar[i] + "\t";
}
JOptionPane.showMessageDialog(null, "Du har nu kastat dina tärningar och kasten blev följande: " + output);
if (tar[0] == 1 && tar[1] == 2 && tar[2]==3 && tar[3] == 4 && tar[4] == 5) {
JOptionPane.showMessageDialog(null, "Grattis, du fick liten stege som är värt 15 poäng");
}
else if (tar[0] == 2 && tar[1] == 3 && tar[2]==4 && tar[3] ==5 && tar[4] ==6) {
JOptionPane.showMessageDialog(null, "Grattis, du fick stor stege som är värt 20 poäng");
}
else{
JOptionPane.showMessageDialog(null, "Tärningskastet resulterade i varken liten stege eller stor stege");
}
}
else if(starta == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Programmet kommer nu att stängas ner");
System.exit(0);
}
String startaom;
startaom = JOptionPane.showInputDialog("Vill du spela igen? Skriv J för att spela igen");
fortsatta = startaom.charAt(0);
}while(fortsatta == 'j');
}
}
I know you're only doing a simplified version of Yahtzee, so first, here is the simple way to check for three-of-a-kind:
if ((tar[0] == tar[1] && tar[1] == tar[2]) ||
(tar[1] == tar[2] && tar[2] == tar[3]) ||
(tar[2] == tar[3] && tar[3] == tar[4])) {
// found 3 of a kind
}
For a more full-blown version, there are a lot of points for various combinations of multiple-of-a-kind in the lower section:
Three-Of-A-Kind
Four-Of-A-Kind
Full House (Three-Of-A-Kind + Two-Of-A-Kind)
Yahtzee (Five-Of-A-Kind)
and for the extended Yatzy version (not Yahtzee):
One-Pair (Two-Of-A-Kind)
Two-Pair (Two-Of-A-Kind + Two-Of-A-Kind)
and for the upper section you need to count how many of a certain number is present.
So, you should start by doing the counts-by-number:
int[] count = new int[6];
for (int i = 0; i < 5; i++)
count[tar[i]-1]++;
Now find the top two counts:
int topIdx1 = 0, topIdx2 = 0;
for (int i = 1; i < 6; i++)
if (count[i] > count[topIdx1]) {
topIdx2 = topIdx1;
topIdx1 = i;
} else if (count[i] > count[topIdx2]) {
topIdx2 = i;
}
Now you can easily find your combination (and the points if doing Yatzy):
if (count[topIdx1] == 5) {
// Yahtzee
} else if (count[topIdx1] == 4) {
// Four-Of-A-Kind yatzyPoints = 4*(topIdx1+1)
} else if (count[topIdx1] == 3) {
if (count[topIdx2] == 2) {
// Full House yatzyPoints = 3*(topIdx1+1) + 2*(topIdx2+1)
} else {
// Three-Of-A-Kind yatzyPoints = 3*(topIdx1+1)
}
} else if (count[topIdx1] == 2) {
if (count[topIdx2] == 2) {
// Two-Pair yatzyPoints = 2*(topIdx1+1) + 2*(topIdx2+1)
} else {
// One-Pair yatzyPoints = 2*(topIdx1+1)
}
}
And for the upper section, the points are easily calculated:
points = number * count[number-1]
I'm assuming that the rules for Swedish Yahtzee are the same as the rules for Yahtzee in the United States.
How can i make a point system for three of a kind?
I'm assuming you're talking about the lower part of the score sheet.
You write a method that checks if your 5 dice have 3 of the same number, and return the sum of the dice as the score. Return zero if the 5 dice don't have 3 of the same number.
A part of the project is to make a category if you don't get one of the implied point systems, ex if you get (1,1,4,5,6) then the user is gonna get the option to choose which number he wants to pick for maximum points.
Now I'm assuming you're talking about the upper part of the score sheet.
You ask the user which category they wish to apply their points to. You only have to show the categories that have not been previously selected. The user can choose category 2 or 3, with a score of zero, if they wish.
If you're asking about how a computer should play categories, you calculate the category score that loses the minimum number of points from 3 of a kind.
In your example, category 1 would be the first choice, since you only lose one point. Category 2 loses 6 points, category 4 loses 8 points, category 3 loses 9 points, category 5 loses 10 points, and category 6 loses 12 points. As the game progresses, the computer has fewer category choices.
Related
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();
}
I'm creating a little mini game of Hangman. The user has 10 chances to guess, but only 5 lives.
The app works, but will continue after the 5th life, even though, I was hoping it would throw the player out of that loop.
The instantiable class (Hangman.java) is working without problems.
The secret word is "julie" as described in the instantiable class.
My App class:
import javax.swing.JOptionPane;
public class HangmanApp {
public static void main(String args[]) {
String input, secret, result, playAgain;
char guess;
int i, j, k, lives;
Hangman myHangman = new Hangman();
do{
JOptionPane.showMessageDialog(null, "Hello, welcome to Hangman! You have 10 chances but only 5 lives! Best of luck");
lives = 5;
for (j = 10; j > 0; j--) {
while (lives >= 0){
input = JOptionPane.showInputDialog(null, "Please enter a letter");
guess = input.charAt(0);
//process
myHangman.setGuess(guess);
myHangman.compute();
result = myHangman.getResult();
if ((input.charAt(0) == 'j') || (input.charAt(0) == 'u') || (input.charAt(0) == 'l') || (input.charAt(0) == 'i') || (input.charAt(0) == 'e')) {
JOptionPane.showMessageDialog(null, "That letter is in the word! Current correct letters: " + result + ".");
} else {
lives--;
JOptionPane.showMessageDialog(null, "Sorry, that letter is not there. Current correct letters: " + result + ".");
}
//output
//JOptionPane.showMessageDialog(null, "Current correct letters: " + result);
};
lives = -1;
}
result = myHangman.getResult();
secret = myHangman.getSecret();
if (secret.equals(result)) {
JOptionPane.showMessageDialog(null, "Congratulations, you got it!! The word was " + secret + ".");
} else {
JOptionPane.showMessageDialog(null, "Sorry, you didn't get it, better look next time! The word was " + secret + ".");
}
playAgain = JOptionPane.showInputDialog("Do you want to play again? yes/no");
}while (playAgain.equals("yes"));
}
}
Try the following change:
while (lives > 0){
you start at 5 and then go down to 4 3 2 1 AND 0. with the change this will stop at 0
// don't need two nested cycles, you can do it in a single one
// The cycle exits if any one of the conditions fail
// max attempts exhausted or all the lives are lost
// -------------------v v------------------------
for (j = 10, lives=5; j > 0 && lives > 0 ; j--) {
// -------------------------------------^
// j - the number of attempt is decremented for each trial,
// no matter if successful or not
//... the rest of cycle logic, which will decrement the lives
// only in cases of unsuccessful attempts
}
After three invalid entries I need the 3rd time to display something different and revert back to the first loop. Also am not sure how to make this continuous
do{
System.out.print("Enter Rating(-1 to quit): ");
rating = input.nextInt();
}
while (rating == 0 || rating == 1 || rating == 2 || rating == 3 || rating == 4);
System.out.print("Invalid entry. Please enter a whole number "
+ "or enter -1 to quit: ");
rating = input.nextInt();
You can use while (rating < 0 || rating > 4)
Do you mean this?
/**
<P>{#code java Test}</P>
**/
public class Test {
public static final void main(String[] ignored) {
int iterationCount = 5;
for(int i = 0; i < iterationCount; i++) {
if(i == 2) { //Index of 3 is 2
System.out.println("Printing something special on the third iteration!");
//You could set i back to 0 here, if that's what you want...
} else {
System.out.println("Index " + i);
}
}
}
}
Output:
[C:\java_code\]java Test
Index 0
Index 1
Printing something special on the third iteration!
Index 3
Index 4
I need help I am new to Java programming and I don't know how to fix my code.
I am trying to make a 007 game. I have created the if statements and it isn't looping around. If I add a ! in front of the each statement in the do-while loop it causes a infinity loop.
How can I fix my programming.
import java.util.Scanner;
import java.util.Random;
public class DoubleOSeven {
public static void main(String[] args) {
System.out.println("Let's Play a game of 007 ");
System.out.println("You can SHOOT, BLOCK, AND RELOAD");
System.out.println("Both you and I start with one bullet");
Scanner input = new Scanner(System.in);
System.out.println("Let's Start, Enter (shoot, reload , or block) ");
String INput = input.nextLine();
//User and Computer ammo
int Userammo = 1;
int ammo = 1;
//Creates a random number between 1 and 3
Random rand = new Random();
int output = rand.nextInt(3) + 1;
do{
//User chooses shoot
if(INput.equals("shoot")){
Userammo --;
System.out.println("You took a shot, Your ammo count is at: " + Userammo);
//User chooses reload
}else if (INput.equals("reload")){
Userammo ++;
System.out.println("You reloaded, Your ammo count is at: " + Userammo);
//User chooses block
}else if(INput.equals("block")){
System.out.println("You blocked, Your ammo count is at: " + Userammo);
//If random is 1 shoot
}if(output == 1){
ammo ++;
System.out.println("I took a shot at you, My ammo count is at: " + ammo);
//If random is 2 block
}else if(output == 2){
System.out.println("I blocked, My ammo count is at: " + ammo);
//If random is 3 reload
}else if(output == 3){
ammo ++;
System.out.println("I reloaded, My ammo count is at: " + ammo);
//If both User and Computer shoot
}if(output == 1 && INput == "shoot"){
System.out.println("It's a tie you we both die");
}
}while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
}
}
while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
should be
while((output == 3 && INput.equals("shoot")) || (output == 1 && INput.equals("reload")) || (output == 1 && INput.equals("shoot")));
First of all: In order for the loop to work well, the question to the user and the computer random decision have to be inside the loop. In this way each loop has a new set of values for the variables.
// Declare variables
String INput = "";
Random rand = new Random();
int output = 0;
do{
// Ask user
System.out.println("Enter (shoot, reload , or block) ");
INput = input.nextLine();
// Computer decision
output = rand.nextInt(3) + 1;
...
Second: You need to have an explicit decision when to terminate the loop (ie the game). This can be done with one of the following
the user wants to end the game (that needs one more option quit in the user choices)
the computer wants to end the game (that needs a forth random number that means quit).
some condition from the combination of user/computer ammo and user/computer shoot. That is you can end the game if some player is shot and has zero ammo.
In all these cases you need to
declare a variable for the end of the game before the loop
decide what to do in the loop
continue the loop if not end of game
This is snippet for this:
boolean endOfGame = false;
...
do {
...
if ( INput.equals("quit")
|| (INput.equals("shoot") && ammo == 0)
|| (Userammo == 0 && output == 1) ) {
endOfGame = true;
}
...
} while (!endOfGame);
You could have the same efect if you put the decision in the while,
but in this way the decision for the end of game is more clear.
It is also possible to set the endOfGame to true in many different places in the loop.
Edit: Some notes on coding style etc
It is a common good practice the names of the variables to start with low case letters (eg instead of Userammo use userAmmo). Names starting with capital letters denote classes.
It makes the code easier to read if the names have some meaning. For example I would suggest the following changes for some of your variables
INput → userAction
Userammo → userAmmo
output → compAction
ammo → compAmmo
Use final constants to give meaning to numbers or strings that appear in your code repeatedly.
Start the if statement on a new line. (else if on the same line is ok)
Using these you could have written (and some comments are not needed)
public class DoubleOSeven {
public static final String S_SHOOT = "shoot";
public static final String S_BLOCK = "block";
public static final String S_RELOAD = "reload";
public static final int I_SHOOT = 1;
public static final int I_BLOCK = 2;
public static final int I_RELOAD = 3;
...
System.out.println("Enter ("+ S_SHOOT + ", " + S_RELOAD + " or " + S_BLOCK + ") ");
...
} else if(userAction.equals(S_BLOCK)){
System.out.println("You blocked, Your ammo count is at: " + userAmmo);
}
if(compAction == I_SHOOT){
compAmmo--; // I changed ++ to -- in order to be a fair game
System.out.println("I took a shot at you, My ammo count is at: " + compAmmo);
} else if(compAction == I_BLOCK){
System.out.println("I blocked, My ammo count is at: " + compAmmo);
...
As per your condition as below
while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
the loop will be executed only if the 3 conditions are true.
You need to make some changes in your condition
All your && cases that are evaluated for this loop result in a false.
Let's say, T for all true cases and F for all F cases
If T&&T&&T then yes we = T (the case for adding !)
If T&&F&&F then F
IF F&&T&&F then F
...
IF F&&F&&F then F
So you need to re-evaluate what condition you want to cause to loop.
Are we looking for
(output==3 && Input=="shoot") || (output==1 && input=="reload") || (output==1 && input=="shoot")
to cause the next iteration?
This would make the case, where any of them are T, we get T. If all of them are F, then we get F.
I am writing a simple craps simulator for Java class and for some reason, it is having trouble running correctly. It is supposed to keep track of losses with "point" and wins with "point" but for some reason, those values tend to be 1 or 0 everytime. The losses and wins on first roll seem to be working. Wondering if someone with a fresh set of eyes can figure out where I messed up. Thank you!
import java.util.Scanner;
import java.util.Random;
class CrapsSimulator {
public static void main(String[] args) {
// Set up values we will use
int lossfirstroll = 0;
int winfirstroll = 0;
int losswithpoint = 0;
int winwithpoint = 0;
boolean gameover = false;
int point = 0;
// Loop through a craps game 100 times
for (int i = 0; i < 100; i++) {
// First roll -- random number within 2-12
Random rand = new Random();
int random = rand.nextInt(11) + 2;
// Win on first roll
if (random == 7 || random == 11) {
winfirstroll++;
gameover = true;
} // Loss on first roll
else if (random == 2 || random == 3 || random == 12) {
lossfirstroll++;
gameover = true;
} else // Player has "point"
{
point = random;
}
// Check to make sure the game hasn't ended already
while (gameover == false) {
// Reroll the dice
random = rand.nextInt(11) + 2;
// Check to see if player has won
if (random == point) {
winwithpoint++;
gameover = true;
}
// Or if the player has lost
if (random == 7) {
losswithpoint++;
gameover = true;
}
// Otherwise, keep playing
gameover = false;
}
}
// Output the final statistics
System.out.println("Final Statistics\n");
System.out.println("Games played: 100\n");
System.out.println("Wins on first roll: " + winfirstroll + "\n");
System.out.println("Losses on first roll: " + lossfirstroll + "\n");
System.out.println("Wins with point: " + winwithpoint + "\n");
System.out.println("Losses with point: " + losswithpoint + "\n");
}
}
either run it through a debugger, or sprinkle System.out.println and see where your logic is failing. Is this homework?
Your problem is the gameover flag. You are always settings it to false again at the end of the inner loop, this will make it run forever.