Vectors in Java - Yahtzee Game - java

I've been asked to program a Yahtzee game on Java. The thing is, I've got a vector of 5 values (which represent dice) and the values are randomly generated with this code:
Value= 1 + (int)(Math.random() * (5.999))
Now, the problem is that once the numbers are generated (or the dice have been thrown), the player is allowed to choose some of the values and hold them (make them constant), so then when the new values are generated, the ones selected don't change.
I've been trying to do this with a boolean variable, but with no luck. What would be the way to keep the values of a vector constant? I'd really appreciate any help, Thanks!

I suggest using a List<Integer>. Remove any values the player does not keep and then fill it back to size 5 at next throw.
Another way would be making a Dice class with randomize() and hold() methods, and have randomize() generate a new random value only if hold() has not been called.

Related

Java ArrayList of Type Class behaves like it only has objects with reference to a global object

I need some help here - I want to do a little card game for learning reasons.
I have a class (Tree/Baum) and an ArrayList "TreeList" of several trees of object Tree.
Now I want to load different random objects of that class in a new ArraList called "PlayersHand".
To do this I have created a for-loop with a tmpObj of type Tree which loads a random index from ArrayList"TreeList" of all Trees. After that it modifies some values of the tmpObj by random (f.e. tree height). Then it adds this whole tmpObject to the ArrayList "PlayersHand".
The Problem is, that when I read out the values of the objects inside PlayersHand the modified values don't show the right way. They always show the last value of the treetype, so f.e. if the last tree of type ACER was 20m high, all the previous trees of type ACER are 20m high too.
It seems like all the objects in the ArrayList "playersHand" are just pointers to the different objects of ArrayList "TreeList".
But why ? And how can I fix it?
The code where the objects are copied:
//"PlayersHand get cards
for(int i=0;i<amountOfCards;i++)
{
int randomNr = (int)(Math.random()* TreeList.size());
Tree tmpTree = TreeList.get(randomNr);
tmpTree.modifyValues();
playersHand.add(tmpTree);
for(int y=0; y<playersHand.size();y++)
{
Tree tmpTree2 = playersHand.get(y);
System.out.println(" - different values of that object shown here - ");
}
}
Edit: Previously I had a more complex scenario. I tried to reduce complexity for better understanding.
I solved it - If someone has the same issue :
You have to use a copy constructor.

Creating Many New Objects

In a program I'm writing, I currently have a class that looks like...
public class Plane {
int[][] planes = new int[5][5];
}
An array is created in this class that has 5 rows and 5 columns. Each row of the array is supposed to contain the details of different 'planes', which are just lines. Each column will contain a different value that is related to the line that I'll have to access later, such as the X and Y values of its start point and its end point, its slope, its y-intercept, etc. In the beginning of the program, though, the user will have the option to create as many lines as they want, and they are requested for the details of that plane, which is currently stored in the "planes" array.
This program would probably be a lot neater if, instead of having a huge array, and creating a new row in that array for every line they wanted to create, I want to create a new "plane" object, and each object will contain the start and end point, slope, and y-intercept details of itself.
The code I have in my main class currently prompts the user, asking them if they want to create a new line. If they say yes, they are then prompted to enter the necessary information about it. After entering the information, they're again prompted, asking if they'd like to create another line, and it repeats. How could I restructure my program to create a new class for each line the user would want to make? How would I reference the variables of those classes when I have to assign values to them? How would I keep track of the classes created?
Any help is appreciated!

Connect Four Program using 2D Arrays in Java

These are the specs for the program I need to complete. Could someone please help me!! I really need to get this program done! Will take any help/advice I can get! Thank you all so much!
You must create two programs named Board and ConFour that have the
following criteria:
1) Proper Introduction
2) Comments that accurately describe the program features
3) Board should have one attribute; a two dimensional array of
character values representing the Connect Four game board. Be sure
to include a constructor (without parameters) that instantiates the
2D-array with 6 rows and 7 columns
4) Board should contain at least four methods. The first method should
be setBoard() which adds an empty character value to every position in the board. The second method, setPosition(), should place the character representing a player (X or O) in the column of their choosing. The third method named checkWinner() should check the board to see if there are four of the same character (X or O) in a row, column or either diagonal. Lastly, printBoard(), should print the contents of the board.
5) ConFour should represent the game play. Have the user(s) enter
START to start the game (they should be able to continuously play after each game)
6) Start each turn by printing the board followed by asking the user to
enter the column they want (be sure to alternate players). If the user enters an incorrect column number, make them re-enter. First player to get four in a row, column or either diagonal is the winner.
Here is a little bit of my thoughts:
To start off, try to make algorithms that check for 4 Xs/Os in a row, which should be 4 for each player. You could also just make 4 algorithms that require you to input the number you are checking for. The directions you need to check are horizontal (check array[i][x+1], where i is the constant in the for loop and x is the number you find to be X or O), vertical (check array[x+1][i] ), right-facing diagonal (check array[i+1][x+1] ), and left-facing diagonal (check array[i-1][x-1].
To print the board, just use 2 for loops that print the values of the array.
For the intro, use a bunch of System.out.println() statements.
The entering of coins is the weird part. You have to create height variables (Or a height function) that stores/checks the height of the coins, then places it on top/next to the other coin. Then check if anyone wins and move on the next player. Keep repeating it until someone wins. Warning: Do not use a while loop. They can't check more than one boolean at a time (but you could put a bunch of if(check) {
boolean itsalltrue = true;
}s, too.
Well, that's all that I can think of (I deliberately did not write the code because I would like you write your own). Enjoy!
Is this for a class? Did you literally just copy and paste the assignment? Try spending some time looking through the notes provided for you, or search more specific questions here. Here's an example of a similar question with code:
Simple 2d array java game

Using a WHILE statement to check against duplicates in Java

I am trying to write a program containing 3 String ArrayLists, where 1 item may be included in all 3 ArrayLists. However, the output must insure that the randomly selected items are all different. As I work through this issue, I am just using numbers so it will be easier to catch. I have been trying to solve this problem for a few days now, and figure there must be something I am overlooking. Here is the code for the method that must have the fault:
private void generateThree() {
// Find the maximum number the random can be.
index = thirdNumberArray.size();
// Initiate the random function.
Random rand = new Random();
// Generate a random number from 1 to the maximum.
randomInt = rand.nextInt(index);
// Access the item in the ArrayList using the random number as the index.
thirdDrawn = thirdNumberArray.get(randomInt);
// Check that the number is different than any previously set numbers.
while ((thirdDrawn.equals(secondDrawn)) || (thirdDrawn.equals(firstDrawn))) {
randomInt = rand.nextInt(index);
thirdDrawn = thirdNumberArray.get(randomInt);
}
// Set the output.
thirdNumberLabel.setText((thirdDrawn));
// Reset the index.
index = 0;
}
So far, the IF statement I use to check the secondDrawn against the firstDrawn has worked perfectly. But the above code still allows the thirdDrawn to display a duplicate of both the firstDrawn and secondDrawn. I know this problem has to be in my loop logic, but I just can't grasp what it is. I have tried multiple different IF statements, but they didn't solve the whole problem. Can anyone give me some feedback or corrections? Thanks in advance.
Any time you generate a number you want to draw, add it to a HashSet<String>. Then, have your if statement conditional check !myHashset.contains(thirdDrawn).

Designing a hand history class for Texas Hold'em in Java

I am trying to come up with a Java hand history class for Texas Hold'em and wanted to bounce an idea off here.
Requirements are that every action is stored and there is an efficient way to traverse each HandHistory object (which would represent a single played hand) to match common 'lines' like the standard continuation bet (i.e. the preflop raiser who was in late position preflop and probably is in position postflop is checked to and then makes a 75%ish pot bet).
Ignore for the moment that the definitions for each of the lines is fuzzy at best. As a first stab, I was thinking of organizing it like so:
public class HandHistory {
private Integer handnumber;
//in case we saw things at showdown, put them here
private HashMap<Player,String> playerHands;
private String flopCards;
private String turnCard;
private String riverCard;
private HashMap<BetRound,LinkedHashMap<Integer,ArrayList<PlayerAction>>> actions;
}
So, for each betround we store a linked hashmap whose keys are integers that are the offsets from first position to act for that betround, so preflop UTG is 0.
We generate the actions in position order already, so use a linked hashmap so we can iterate nicely later and skip over positions that are sitting out,etc.
Each arraylist will contain the actions that that position had in that betround. Most of the time this array will have one element, but in cases like, limps and then calls, it will have two.
Can anyone see a better data structure to use for this?
small change, since holdem has a fixed number of betting rounds, maybe
private HashMap<BetRound,LinkedHashMap<Integer,ArrayList<PlayerAction>>> actions;
could just be:
private LinkedHashMap<Integer,ArrayList<PlayerAction>>[] actions= new ... ;
also, here's a couple of books that may be of interest:
http://www.amazon.com/Poker-strategy-Winning-game-theory/dp/0399506691
http://www.amazon.com/Mathematics-Poker-Bill-Chen/dp/1886070253
class Card {
// ??? probably just an int (0 to 51), but certainly not a String.
// Instead of using class Card below, directly using an int woulb be OK.
}
class Hand {
Set<Card> hand; // size 2
}
class Draw { // not sure of the exact poker name for the 5 cards
Set<Card> flop; // size 3
Card turn;
Card river;
}
class Bet {
Player player;
// or maybe "Double" instead; then amount == null means player dropping out.
// or use 0.0 to mean dropped out.
double amount;
}
class BettingRound {
// Includes initial "entry" and all subsequent calls.
// Should include players dropping out also.
List<Bet> bets;
}
class Game {
Draw draw;
Map<Player, Hand> hands;
// rounds 0 and 1 are special since turn and river are not shown
List<BettingRound> rounds;
}
You should also know how much money each player has, I guess. You could keep track of that with a third field (total cash before the bet) in class Bet.
After thinking about it for a bit more, I think I have answered my own question. I've decided not to try to both store every action in a tabular way and try to get quick lookup of frequency counts for betting lines in the same data structure.
Instead, I am going to use my class above as the database-like storage to disk and use a DAG for the betting lines where the edges are tuples of {action, position, players ahead} and the vertices are frequency counts. I think a DAG is correct over a trie here since I do want multiple edges coming into a vertex since lines with common suffix are considered close.

Categories