Rolling two dice - java

I'm writing a program that is supposed to return the value of rolling two dice. I want the user to be able to select a specified type of die or chose a custom number of sides. So, for example, I chose the triangle die, I would have a 3 sided die.
The variable:
private int die = 1;
private int preselectedSides;
The case in a switch I've made to handle the menu looks like this:
switch(selection)
case 1:
premadeDice(3, 4, 6);
x=1;
break;
The receiving method looks like this:
//premade Dice Selection//
public int premadeDice(int triangle, int rectangle, int cube)
{
String choice;
boolean flag = false;
while (flag == false)
{
System.out.println("Enter in the shape you want your die to be");
System.out.println("A triangle die has 3 sides. If this is what you want, type \"triangle\"");
System.out.println("A rectangle die has 4 sides. If this is what you want, type \"rectangle\"");
System.out.println("A cube die has 6 sides. If this is what you want, type \"cube\"");
choice = sc.next();
if (choice.equalsIgnoreCase("triangle"))
{
System.out.println("You have chosen the triangle die.");
preselectedSides = triangle;
flag = true;
}
else if (choice.equalsIgnoreCase("rectangle"))
{
System.out.println("You have chosen the rectangle die.");
preselectedSides = rectangle;
flag = true;
}
else if (choice.equalsIgnoreCase("cube"))
{
System.out.println("You have chosen the traditonal cube die.");
preselectedSides = cube;
flag = true;
}
else
{
System.out.println("You have not entered in a valid die shape. Try again");
}
}//end while loop
return preselectedSides;
}//end pre-made dice method
I created a getter to get access to that returned value:
//getter for Die
public void getDie()
{
System.out.println(preselectedSides);
}
Call it like this:
test.getDie();
And I get the following output for a cube (or for the other shapes, I keep getting 1 along with the value)
1
6
I've tried finding this logic error but I don't see it. Why does it keep outputting the number one? Ask for clarification if needed.

This seems like an awful lot of code. You can simplify it like so:
public class Die
{
int sides;
//get/set/constructor
...
}
public class DieRoller
{
Die die;
public int roll()
{
Random generator = new Random();
return generator.nextInt(this.die.getSides());
}
}
You can run it like so:
public static void main(String[] args)
{
System.out.println("Number of sides?");
Scanner sc = new Scanner(System.in);
Die currentDie = new Die(sc.nextInt());
System.out.println("Rolling");
DieRoller roller = new DieRoller(currentDie);
int sideRolled = roller.roll();
System.out.println(String.format("You rolled %d on your %d sided die",sideRolled,currentDie.getSides()));
}

Related

How to fix a variable from a class not being subtracted in a method?

The gist of this assignment is that there are two players who take a stick out of a pile. I made a class that has the number of sticks available. There is a method that is called to remove sticks. However when I try to remove sticks the number of sticks doesn't change. Therefore the game not being able to end because there are still sticks "left".
I've tried using int sticks to be subtracted. The total amount of sticks changes but only in the method in which they are subtracted. The number of sticks don't change in the main method.
I decided to make use classes as I saw on this site that that is how this issue can be fixed. I've had no success with it.
So I made a class that has the amount of sticks so now the number of sticks is the same for each method. The same issue persists. One that changes the number of sticks in the getSticksRemove() method but not main() or getSticksLeft().
//Main Class
public class Main {
//Method to remove sticks which considers different scenarios.
public static int getSticksRemove(int sticks) {
sticks = StickPile.getValue(StickPile.value);
Scanner input = new Scanner(System.in);
print ("How many sticks to remove?(1-3)");
int x = input.nextInt();
if( x>=1 && x<=3) {
sticks -= x;
}else if(sticks < 3 && x ==2 ) {
print("Not enough sticks left.");
getSticksRemove(sticks);
}else if (x>3) {
sticks -=3;
}else { `enter code here`
sticks-=1;
}
print(sticks);
return sticks;
}
//Main method
public static void main(String [] args) {
StickPile stickPile = new StickPile();
int turnP1 = 0;
int turnP2 = 0;
int sticks = 0;
print("How many sticks are there initially? (1-100)");
StickPile.setValue();
sticks = StickPile.getValue(StickPile.value);
//This is the loop that determines when to stop the game
while(sticks != 0) {
System.out.print("Player 1: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP1++;
System.out.print("Player 2: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP2++;
}
if(turnP1 % 2 == 0 && turnP2 % 2 == 1) {
System.out.println("P2 Loses");
}else {
System.out.println("P1 Loses");
}
}
}
// This StickPile class is the one I made to store the number of sticks.
public class StickPile {
static Scanner input = new Scanner(System.in);
public static int value;
public static void setValue() {
value = input.nextInt();
}
public static int getValue(int x) {
x = value;
System.out.println(x);
return x;
}
I expect to enter a number of sticks to remove from the pile. Ex. PileAmount: 20--> Remove: 12--> PileAmount: 8.
However, I get Ex. PileAmoun: 20 --> Remove: 5--> PileAmount: 20,
You're ignoring the return of getSticksRemove. You can't reassign the parameter to effect the number outside of the function.
Just use the return value:
sticks = getSticksRemove(sticks)
Make that change in both places.

Random generator always amounting to 0 (Java)

I am working through Head First Java, and my Random generator is amounting to 0. Here are my classes:
This is my class with the main method.
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
This is my player object class:
import java.util.Random;
public class Player {
int number = 0; //Where the guess goes
public void guess() {
//random1 is in GuessGame
Random random2 = new Random();
int number = random2.nextInt(10);
System.out.println("I'm guessing " + number);
}
}
Finally, this is the class where most of the code is happening.
import java.util.Random;
public class GuessGame {
//Guessgame has three instance variables for the three Player objects
Player p1;
Player p2;
Player p3;
public void startGame() {
//Create three Player objects and assign them to the three Player instance variables
p1 = new Player();
p2 = new Player();
p3 = new Player();
//Declare three variables to hold the three guesses the players make
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
//Declare three variables to hold a true or false based on the player's answer
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
//Make a "target" number that the players have to guess
Random random = new Random();
//Generate a number between 0 and 9
int targetNumber = random.nextInt(10);
System.out.println("I'm thinking of a number between 0 and 9...");
while (true) {
System.out.println("Number to guess is " + targetNumber);
//Call each player's guess() method
p1.guess();
p2.guess();
p3.guess();
/*
Get each player's guess (the result of their guess() method
running) by accessing the number variable of each player
*/
guessp1 = p1.number;
guessp2 = p2.number;
guessp3 = p3.number;
System.out.println("Player one guessed " + guessp1);
System.out.println("Player two guessed " + guessp2);
System.out.println("Player three guessed " + guessp3);
/*
Check each player's guess to see if it matches the target number. If a player is right, then set that player's variable to be true (remember, we set it false by default)
*/
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
//If player one OR player two OR player three is right... (the || operator means OR)
if (p1isRight || p2isRight || p3isRight) {
System.out.println("We have a winner!");
System.out.println("Player one got it right? " + p1isRight);
System.out.println("Player two got it right? " + p2isRight);
System.out.println("Player three got it right? " + p3isRight);
System.out.println("Game is over.");
break; //Game over, so break out of the loop
}
else {
//We must keep going because nobody got it right!
System.out.println("Players will have to try again.");
} //end if/else
} //end loop
} //end method
} //end class
I am new to these forums, so if I did something wrong please let me know :)
Does anyone know why this isn't working?
Thanks,
Lyfe
You are storing random number in local variable and you think you set it in instance variable
at line
int number = random2.nextInt(10);
change it to
this.number = random2.nextInt(10);
that atleast solves stated problem.
Also See
Java Variables

Why am i not able to regenerate a new game board after user respond yes to if the want to restart?

https://cse.sc.edu/~shephejj/csce146/Homework/Homework01.html
import java.util.*;
public class MineSweep {
enum Spaces{Empty,Player,Cone,Mine}
public static final int Board_Size=10;
public final static double Percent_Mine = 0.1;
public static void main(String[]arg){
Spaces[][] Board= new Spaces[Board_Size][Board_Size];//Creates new multidimensional array.
int numOfMoves=0;
int positionX=0;
int positionY=0;
boolean isOver=false;
boolean isDead = false;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Scanner Scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
if(isDead==true){
Board=generateBoard();
}else{
while(isOver==false)
{
for(int y=0;y<Board.length;y++)
{
for(int x=0;x<Board[y].length;x++)
{
switch(Board[x][y])
{
case Empty:
System.out.print("_");
break;
case Player:
System.out.print("X");
break;
case Mine:
System.out.print("!");
break;
case Cone:
System.out.print("^");
break;
default:
System.out.print("?");
break;
}
}
System.out.println(" ");
}
System.out.println("Enter either -1,0,1 to move in the X or 9 to quit");
int directionX = Scan.nextInt();
if(directionX==9)
{
System.out.println("Game Over");
System.exit(0);
}
System.out.println("Enter either -1,0,1 to move in th Y");
int directionY= Scan.nextInt();
if(directionX<-1 || directionX>1){
System.out.println("Invalid Input X");
directionX=0;
}
if(directionY <-1 || directionY>1)
{
System.out.println("Invalid input Y");
directionY = 0;
}
Board[positionX][positionY] = Spaces.Empty;
positionX+=directionX;
positionY+=directionY;
if(positionX < 0)
{
positionX = 0;
}
else if(positionX>Board_Size-1)
{
positionX = Board_Size-1;
}
if(positionY < 0)
{
positionY = 0;
}
else if(positionY> Board_Size-1)
{
positionY = Board_Size-1;
}
String retry;
if(Board[positionX][positionY]==Spaces.Mine)
{
isDead=true;
System.out.println("Boom! Dead!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
retry = scan2.nextLine();
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
else if (retry.equalsIgnoreCase("No"))
{
System.out.println("Goodbye!");
System.exit(0);
}
}
if(Board[positionX][positionY]==Spaces.Cone)
{
System.out.println("You win!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
}
Board[positionX][positionY] = Spaces.Player;
}
}
}
public static Spaces[][] generateBoard(){
int positionX=0;
int positionY=0;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Spaces[][] Board= new Spaces[Board_Size][Board_Size];
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
return Board;
}
}
In the code is above.Everything works, i'm just unable to create a new game board.I create a method called "generateboard()" and I call that method if "isDead= true" and user responds yes to if they want to retry.Please Help !
First of, you should really try to clean up your code a bit. It has some duplication and it is kinda hard to read. That said, I think your problem lies with this piece of code:
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
You are generating a new board, but you are not telling your program to use it. Change generateBoard() to Board = generateBoard();. Also you forget to reset your players position to 0,0.
Now I would like to give you some pointers on how you could clean up your program. The first part of your main method is basically a copy paste of your generate board method, this means that you could instead reuse that method to initialize the board.
After generating your board, the first if statement if (isDead == true) will never be true, because you just set isDead = false. Just do away with this if statement. This actually makes your isDead variable unused, because you don't use it otherwise.
You probably want to either return the starting position of the player from the generateBoard method, or take the starting position as arguments to the method in order to know where the position of the player is. In your example your player always starts at 0,0, but one could imagine that you would want to change that some time.
A couple of things to note:
In Java, variables usually start with a lower case letter (use "board" instead of "Board").
Enums in Java are usually all UPPER CASE (EMPTY instead of Empty etc.).
You don't need to use == false or ==true on boolean values, you could simply write: if (isDead).
You could also do with dividing your code into methods, but I'll leave that as an exercise for you. Also, you don't actually do anything when a player wins in the game.

Dice rolling program, but I need to transfer input data from a different class

I'm trying to create a program that will roll 2 different die, that could either be automatically 6 sided or custom sided as decided by the user. As of right now I've gotten this far and need help figuring out how to get anything to happen from the roll() method, I've tried running it and it won't give me the random int it should.
Any ideas?
import java.util.*;
import java.lang.*;
public class RollOfTheDice
{
public static void main(String[] args)
{ Die firstDie, secondDie, face;
firstDie = new Die();
secondDie = new Die();
face = new Die();
face.getSides();
firstDie.roll();
secondDie.roll();
System.out.println("First die roll results:.");
}
}
class Die
{
int numberOfSides; //field value
public Die() //constructor
{ numberOfSides = 6;
}
public int getSides()//get method
{ Scanner inputDevice = new Scanner (System.in);
System.out.println("If looking for a custom sided die, please enter number of sides now:");
numberOfSides = inputDevice.nextInt();
return numberOfSides;
}
public void setSides(int Sides) //setmethod
{
numberOfSides = Sides;
}
public int roll()
{
//return a random-generated integer value between 1 and amount of sides
int rollResult = ((int)(Math.random() * 100)% numberOfSides + 1);
return rollResult;
}
}
Since an answer has already been accepted, I figured I'd give a few pointers;
public int getSides()//get method
{ Scanner inputDevice = new Scanner (System.in);
System.out.println("If looking for a custom sided die, please enter number of sides now:");
numberOfSides = inputDevice.nextInt();
return numberOfSides;
}
I recommend not doing IO during getSides() which then has a side-effect of setting the number of sides in your die.
instead, have the main method run the "askForSides" method (which contains the scanner). and then pass this argument into a setSides() method.
secondly, I recommend that instead of your current constructor which sets the sides to a fixed 6 you replace it with:
public Die() //constructor
{
numberOfSides = 6;
}
public Die(int sides) {
this.numberOfSides = sides;
}
Even better (well, I like it anyway) is:
public Die() //constructor
{
this(6);
}
public Die(int sides) {
this.numberOfSides = sides;
}
this way only 1 constructor actually sets the sides, the other simply supplies a default. this makes refactoring easier in the long run.
if you have a constructor that takes sides as an argument, you can use that instead of the setSides method :)
Firstly, you do not actually println your roll result ever.
So to get that basic output, you can change the last 3 lines of your main() method to the following:
int firstRoll = firstDie.roll();
int secondRoll = secondDie.roll();
System.out.println("First die roll results:" + firstRoll);
System.out.println("Second die roll results:" + secondRoll);
This should at least get you to show the two dice rolls.
You did not simply forget to print out the actual value?
int first = firstDie.roll();
System.out.println("First die roll results: " + first);
You are calling roll, but not doing anything with the value that it returns.

Object Oriented Approach for a simple game

I am working on building a simplified version of this game. The problem states that you can have a computer that is smart or stupid but i have decided that to exclude that feature for now and decided to only go with a computer that picks a random amount of objects. I posted a question earlier and worked on it. (https://softwareengineering.stackexchange.com/questions/244680/object-oriented-design-of-a-small-java-game/244683#244683)
So initially i only had designed one class. But now i have designed 3 classes as stated by the problem. I have a pile class , a player class and a game class (also my main class).
I have so far coded the Pile and Player class. I started coding the Game class aswell however i am stuck now as i dont know how to make the game class interact with the Player and Pile class. I basically determine who's turn it is first and then rotate turns till the pile of objects is complete and declare a winner...I don't know how to make the different classes interact with each other . SO i would highly appreciate if someone can guide me further and help me finish this simple game.
I sincerely apologize if i have asked a bad question. This is my first such program i am doing in java dealing with multiple classes so it is a little confusing. I do not want anyone write code but even mentioning or telling me i should make so and so methods etc will be great !
HERE IS THE CODE I HAVE SO FAR.
PILE CLASS
package Nim;
import java.util.Random;
public class Pile {
private int initialSize;
public Pile() {
}
Random rand = new Random();
public void setPile() {
initialSize = (rand.nextInt(100 - 10) + 10);
}
public void reducePile(int x) {
initialSize = initialSize - x;
}
public int getPile() {
return initialSize;
}
public boolean hasStick() {
if (initialSize > 0) {
return true;
}
else {
return false;
}
}
}
PLAYER CLASS
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Player {
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int theType) {
type = theType;
}
Scanner in = new Scanner(System.in);
// n is number of marbles left in the pile
public int makeMove(int n) {
int max = n / 2;
int grab;
if (type == HUMAN) {
System.out.println("There are " + n
+ " marbles in total. However you can only"
+ "grab no more than " + max + " marbles");
System.out.println("Please Enter the number of marbles to grab: ");
grab = in.nextInt();
while (grab > max || grab < 0) {
System.out.println("You have entered a illelgal value. Please enter a legal value: ");
grab = in.nextInt();
}
return grab;
}
else {
Random rand = new Random();
grab = (rand.nextInt(n / 2 - 1) + 1);
System.out.println("Computer has grabbed: " + grab + " marbles");
return grab;
}
}
public void updateTurn(int n) {
type = n;
}
}
GAME CLASS (in progress)
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Game {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println(welcome());
Pile marbles = new Pile();
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
marbles.setPile();
System.out.println("There are total: " + marbles.getPile()
+ " marbles in the Pile.");
System.out.println("Time for a toin coss to see who goes first!");
System.out.println("Please Select heads(0) or Tails(1): ");
int choice = in.nextInt();
int tossResult = rand.nextInt(2);
boolean playerTurn = false;
boolean computerTurn = false;
if (choice == tossResult) {
System.out.println("You have won the Coin Toss! You will go first!");
human.updateTurn(0);
playerTurn = true;
}
else {
System.out.println("Computer has won the coin toss! Computer will go first");
computer.updateTurn(1);
computerTurn = true;
}
while (marbles.getPile() > 0 && marbles.hasStick()) {
while (playerTurn) {
int removeMarbles = human.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
computerTurn = true;
playerTurn = false;
}
while (computerTurn) {
int removeMarbles = computer.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
playerTurn = true;
computerTurn = false;
}
}
}
private static String welcome() {
return "Welcome to the Game of Nim";
}
}
So I'm going to take a step back and look at your class diagram.
You have three classes: Pile, Player, and Game. Pile can represent the pile at the center. Game can be the class with the main method that manages everything. And Player? Well, since you're having one Player class for all three (or two) possible states (Human, Dumb, and Smart) it should be pretty easy to implement.
Let's start with Game. It need to contain two instances of Player (human and computer), and an instance of Pile. It also needs to have a loop that goes until the game is over. So let's start to come up with a basic implementation:
Starting with Pile:
private int size;
public Pile(int newSize) {
size = newSize;
}
public boolean takeMarbles(int amount) {
size -= amount;
if (size < 1)
return false;
return true;
}
The constructor is pretty self explanatory. The takeMarbles method is returning false if the player lost, and true if they're still in the game.
Now on to Player:
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int type) {
this.type = type;
}
Those two static fields may seem a little out of place, but it will come together in a second. On to the Game class:
Pile pile = new Pile(size);
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
Now we have a pile with a certain size, and two players that differ by type. This is how we're using the classes.
Now we need to get the main game loop working. Basically, just add an update() method to Player that depends on it's type (ie prompts for input if player, randomly decides if computer). The update method should return the amount of marbles to take. Then create a loop in the main method in Game. The loop will call update of the player and the computer repeatedly until someone loses (takeMarbles returns false). Then it will break out of the loop and print the output.
This is the basic idea, good luck and feel free to ask more questions!

Categories

Resources