Why does my simple poker program continue to draw the same cards? - java

I'm learning Java for my own and i have this problem:
I created a poker program, and every time, both the AI and I draw nothing but the Ace of Spades (5 each) every round. How can I fix this?
import java.io.IOException;
import java.util.Scanner;
public class poker {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int score1 = 0,score2 = 0;
for (int i=0; i<10; i++) {
int[][] previous_cards = new int[0][2];
int[][] hand1 = generate_hand(previous_cards);
int[][] sorted1 = sort_hand(hand1);
System.out.println("Round "+(i+1)+": ");
System.out.print(" Your hand: ");
print_hand(sorted1);
int identify_hand1 = identify_hand(sorted1);
System.out.print(" ");
print_identify_hand(identify_hand1);
System.out.println();
int[][] hand2 = generate_hand(hand1);
int[][] sorted2 = sort_hand(hand2);
System.out.print(" Computer hand: ");
print_hand(sorted2);
int identify_hand2 = identify_hand(sorted2);
System.out.print(" ");
print_identify_hand(identify_hand2);
System.out.println();
int compared = compare_hands(sorted1,sorted2);
if (compared==-1)
System.out.println(" You win this round!");
else if (compared==1)
System.out.println(" The computer wins this round!");
else System.out.println("Draw!");
score1 += (compared<0)?1:0;
score2 += (compared>0)?1:0;
System.out.println(" Score: You:"+score1+" - Computer:"+score2);
input.nextLine();
}
if (score1<score2)
System.out.println("The computer won with: "+score2+"-"+score1+".");
else if (score1==score2)
System.out.println("Draw: "+score1+"-"+score2+".");
else System.out.println("You won with: "+score1+"-"+score2+".");
}
public static int[][] generate_hand(int[][] previous_cards) {
int[][] hand = new int[5][2];
return hand;
}
public static int[] generate_card() {
int[] card = new int[2];
card[0] = (int) (Math.random()*13 + 2);
card[1] = (int) (Math.random()*4 + 1);
return card;
}
public static int compare_2_cards(int[] card1, int[] card2) {
return 0;
}
public static void print_hand(int[][] hand) {
System.out.print(card_to_String(hand[0])+", ");
System.out.print(card_to_String(hand[1])+", ");
System.out.print(card_to_String(hand[2])+", ");
System.out.print(card_to_String(hand[3])+", ");
System.out.print(card_to_String(hand[4]));
}
public static String card_to_String(int[] c) {
String card = "";
if (2<=c[0] && c[0]<=10)
card += c[0];
else if (c[0]==11) card += "Jack";
else if (c[0]==12) card += "Queen";
else if (c[0]==13) card += "king";
else card += "Ace";
card += " of ";
if (c[1]==1) card += "hearts";
else if (c[1]==2) card += "diamonds";
else if (c[1]==2) card += "clubs";
else card += "spades";
return card;
}
public static int[][] sort_hand(int[][] hand) {
int[][] sorted = new int[5][2];
return sorted;
}
public static void print_identify_hand(int identify_hand) {
if (identify_hand==1)
System.out.print("(straight flush)");
else if (identify_hand==2)
System.out.print("(four of a kind)");
else if (identify_hand==3)
System.out.print("(full house)");
else if (identify_hand==3)
System.out.print("(four of a kind)");
else if (identify_hand==4)
System.out.print("(flush)");
else if (identify_hand==5)
System.out.print("(straight)");
else if (identify_hand==6)
System.out.print("(three of a kind)");
else if (identify_hand==7)
System.out.print("(two pairs)");
else if (identify_hand==8)
System.out.print("(one pair)");
else
System.out.print("(nothing - high hand comparison)");
}
public static int compare_hands(int[][] hand1,int[][] hand2) {
// IMPLEMENT: compare 2 cards
return 1;
}
public static int identify_hand(int[][] hand) {
if (hand[0][1]==hand[1][1] && hand[1][1]==hand[2][1] && hand[2][1]==hand[3][1] && hand[3][1]==hand[4][1] && // compare that they have the same suit
hand[0][0]+1==hand[1][0] && hand[1][0]+1==hand[2][0] && hand[2][0]+1==hand[3][0] && hand[3][0]+1==hand[4][0]) // compare card numbers
return 1;
if (hand[0][0]==hand[1][0] && hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0]) // compare card numbers
return 2;
if (hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0] && hand[3][0]==hand[4][0]) // compare card numbers
return 2;
return 9;
}
}

Your int[][] hand objects are empty.
The generate_hand method returns an empty array, sort_hand returns another empty array, the other methods don't alter the array at all.
You end up passing empty (for int arrays, that means that each index contains 0) arrays to card_to_String, which then displays the result for c[0] == 0 and c[1] == 0, you got it...this is Ace of spades.

Related

How to return my getWin with more than just true or false

I'm trying to get my program to take multiple different return statements so i can have a win split and lose rather than just win or lose and cant seem to figure out how to do it. My program is made to be able to have either you win and it doubles your bet that you made. If you tie you get your money back. if you lose you lose your bet. Ive gotten win and lose to work previously with using a booelean and returning true or false but needed a way to add in a way to do split.
I've tried multiple methods I've seen online but to no avail any help would be appreciated.
//Import Random Number Generator
import java.util.Random;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
private String Win;
private String Lose;
private String Split;
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
Win = "Win";
}
else if(sum < other.getSum()){
Lose = "Lose";
}
else if(sum == other.getSum()){
Split = "Split";
}
return Win;
}
}//end main
import java.util.Scanner;
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100;
int bet;
int winnings;
int multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
System.out.println(you.getWin());
if(you.getWin()){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else{
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}//end class
I expect to be able to get different return statements that way I can actually set a win aspect a lose aspect but also a split aspect if both players tie.
You have three results to return which are: WIN, LOSE and TIE right?
In that case you have to use three different variables like,
public String Win = "Win",Lose = "Lose",Split = "Split";
and use other variable to store result like result and return this result in getWin(). See below code:
import java.util.Random;
import java.util.Scanner;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
public String Win = "Win",Lose = "Lose",Split = "Split";
private String result = "";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end main
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100,bet,winnings,multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
String result = you.getWin(enemy);
System.out.println(result);
if(result == you.Win){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else if (result == you.Lose){
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}else{
System.out.println("You Split");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}

Okay so I'm coding a roll the dice game on java

This is the code I have, but I want it to be able to roll the dice based on the number of trials the user inputs and then display the frequencies of each face.
This code isn't working as I would expect.
Also I would like to change the switch cases to if and else if statements, if anybody could help me out with that would be amazing, I've been working on this for a while now.
import java.util.Random;
import java.util.Scanner;
public class DieRoll {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random randomNumbers = new Random();
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int trials;
int face;
System.out.println("Please enter the number of trials");
Scanner scan= new Scanner (System.in);
trials= scan.nextInt();
for(int rolls= 1; rolls==trials; rolls++);{
face= randomNumbers.nextInt(6) + 1;
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++one; // increment the 1s counter
break;
case 2:
++two; // increment the 2s counter
break;
case 3:
++three; // increment the 3s counter
break;
case 4:
++four; // increment the 4s counter
break;
case 5:
++five; // increment the 5s counter
break;
case 6:
++six; // increment the 6s counter
break; // optional at end of switch
}
}
System.out.println( "Face\tFrequency" ); // output headers
System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
one, two, three, four,
five, six );
scan.close();
}
}
In your for loop:
Remove the semicolon (;) just after the for(int rolls= 1; rolls==trials; rolls++) line.
Change:
for(int rolls= 1; rolls==trials; rolls++)
to:
for(int rolls= 1; rolls<=trials; rolls++)
As far as changing switch to if-else-if, not sure why you would want to do this, but simply write it as:
if(face == 1){
one++;
}
else if(face ==2){
two++;
}
and so on..
Please have a look at this:
public class Main {
private static final Random RANDOM_NUMBER_GENERATOR = new Random();
public static void main(String[] args) {
int numberOfTrials;
int[] facesFrequencies = new int[6];
System.out.println("Please enter the number of trials");
Scanner scanner = new Scanner(System.in);
numberOfTrials = scanner.nextInt();
scanner.close();
for (int numberOfRolls = 1; numberOfRolls <= numberOfTrials; numberOfRolls++) {
int face = rollDice();
if (face == 1) {
facesFrequencies[0] += 1;
} else if (face == 2) {
facesFrequencies[1] += 1;
} else if (face == 3) {
facesFrequencies[2] += 1;
} else if (face == 4) {
facesFrequencies[3] += 1;
} else if (face == 5) {
facesFrequencies[4] += 1;
} else if (face == 6) {
facesFrequencies[5] += 1;
}
}
System.out.println("Face\tFrequency");
for (int i = 0; i < facesFrequencies.length; i++) {
System.out.printf("%d\t\t%d%n", i, facesFrequencies[i]);
}
}
private static int rollDice() {
return RANDOM_NUMBER_GENERATOR.nextInt(6) + 1;
}
}
I've put the results (int one to int six) into an array. facesFrequencies[0] will be the same as int one.
The ; after for (...) is syntactically incorrect.
Switch statement is replaced with if statement.

Displaying results for tic tac toe app

I'm currently writing a program that creates the game tic tac toe. The app as it is right now has two people play at against each other, taking turns entering the row and column number. The main problem I'm having with this program is that I cannot get it to display the results of whether one person wins or loses or both players tie. If anyone has any suggestions as to how I can solve this that would be great. Thanks again for your time.
import java.util.Scanner;
public class ticTacToeApp {
// 1. GAME CONSTANTS
static final int WIN = 1;
static final int LOSE = 0;
static final int TIE = 2;
static final int GAME_IN_PROGRESS = 3;
static final String PLAYER = "X";
static final String OPPONENT = "O";
static final String EMPTY = " ";
// 2. INPUT STREAM
static Scanner in;
public static void main(String[] args) {
// 3. BUILD THE TIC TAC TOE 3X3 BOARD OF STRINGS
String[][] board = { { EMPTY, EMPTY, EMPTY }, { EMPTY, EMPTY, EMPTY },{EMPTY, EMPTY, EMPTY } };
// 4. INSTANTIATE THE SCANNER FOR INPUT
in = new Scanner(System.in);
// 5. GAME ENGINE
drawBoard(board);
int moveResult = GAME_IN_PROGRESS; // STATUS OF THE GAME AND AFTER A
// MOVE
while (moveResult == GAME_IN_PROGRESS) {
// PLAYER MOVES AND BOARD IS CHECKED FOR A RESULT
getMove(board, PLAYER, in);
drawBoard(board);
if (moveResult != GAME_IN_PROGRESS)
break;
// OPPONENT MOVES AND THE BOARD IS CHECKED FOR A RESULT
getMove(board, OPPONENT, in);
drawBoard(board);
moveResult = boardResults(board);
}
// 6. ONCE THE GAME HAS ENDED, DISPLAY IT IS AS A WIN, LOSE, OR TIE.
if (moveResult == WIN)
System.out.println("You win.");
else if (moveResult == LOSE)
System.out.println("You lost.");
else
System.out.println("You tied.");
}
public static int boardResults(String[][] board) {
// TASK 1: BUILD AN ARRAY CONTAINING ALL THE ROW, COLUMN, AND
// DIAGONAL STRING ARRANGEMENTS ON THE CURRENT
// TIC TAC TOE BOARD.
String[] waysToWin = new String[8];
int i = 0; // INDEX TO wayToWin
for (int r = 0; r < 3; r++) {
String str = " ", stc = " ";
for (int c = 0; c < 3; c++) {
str += board[r][c];
stc += board[c][r];
}
waysToWin[i++] = str;
waysToWin[i++] = stc;
// ADD 2 DIAGONALS
waysToWin[i++] = board[0][0] + board[1][1] + board[2][2];
waysToWin[i++] = board[0][2] + board[1][1] + board[2][0];
// TASK 2. CHECK IF ANY OF THESE ARRANGEMENTS CONTAIN A WINNING
// "XXX" OR
// "OOO"
// NOTE: AN "XXX" IS WIN AND AN "OOO" IS LOSE.
for (int p = 0; p < 8; p++) {
if (waysToWin[p].equals("XXX"))
return WIN;
if (waysToWin[p].equals("OOO"))
return LOSE;
// TASK 3. CHECK IF THE BOARD IS FULL (TIE) OR IF THE GAME IS
// STILL IN
// PROGRESS
if (board[0][0] == EMPTY || board[0][1] == EMPTY || board[0][2] == EMPTY || board[1][0] == EMPTY
|| board[1][1] == EMPTY || board[1][2] == EMPTY || board[2][0] == EMPTY || board[2][1] == EMPTY
|| board[2][2] == EMPTY)
return GAME_IN_PROGRESS;
}
}
return i;
}
public static void drawBoard(String[][] board) {
for (int row = 0; row < board.length; row++) {
System.out.println("___________");
for (int col = 0; col < board[row].length; col++) {
System.out.print("|" + board[row][col] + " ");
}
System.out.println("| ");
}
System.out.println("___________");
}
public static void getMove(String[][] board, String whoseMove, Scanner in) {
int[] xy = new int[2];
for (;;) {
System.out.print("You are " + whoseMove + ". ");
System.out.println("Enter the row and column of your move: ");
xy[0] = in.nextInt();
xy[1] = in.nextInt();
if (board[xy[0]][xy[1]].equals(EMPTY))
break;
System.out.println("You must choose an empty space.");
}
board[xy[0]][xy[1]] = whoseMove;
}
}
I would use a single dimensional array for the board and create an array of winning combinations that indexes into the board. Then loop through the winning combinations and count X's and O's. If you have 3, then declare a winner. Here is a snippet demonstrating:
public class ticTacToeApp {
static final String X = "X";
static final String O = "O";
static final String N = " ";
public static void main(String[] args) {
String[] board = { X,X,O,
N,O,N,
O,N,N };
// combinations to win:
int[][] wins = { {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,6,8}, {0,4,8}, {2,4,6} };
// count x's and o's to win
int x=0, o=0;
// find the winner by indexing the board array from the combinations to win array
// In each combination to win, if all 3 are X's or O's, declare a winner
for(int i=0; i<8; i++) {
x=0; o=0;
for(int j=0;j<3;j++) {
if (board[wins[i][j]] == X) x++;
if (board[wins[i][j]] == O) o++;
}
if (o==3 || x==3)
System.out.println(((x==3) ? "X" : "O") + " wins");
}
}
}

Poker dice game, and I don't know why my methods have errors on them

public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int[] dice = new int[5];
resetDice(dice);
System.out.print("Your current dice: + dice");
rollDice(dice);
System.out.print(dice);
System.out.println();
promptForReroll(dice, inScanner);
System.out.println("Rerolling...");
rollDice(dice);
System.out.println("Your final dice: + dice");
System.out.println(getResult(dice)+"!");
}
private static void resetDice(int[] dice) {
int length = 5;
for(int i = 0; i < length; i++){
dice[i] = 0;
}
}
private static void rollDice(int[] dice) {
int i = 0;
int length = 5;
while(i < length) {
if(dice[i] == 0) {
int roll = (int)(Math.random()*6)+1;
dice[i] = roll;
i++;
}
}
}
private static String diceToString(int[] dice) {
String diceToString =("Your current dice: " +dice[0]+", " +dice[1]+ ", " +dice[2]+ ", " +dice[3]+ ", " +dice[4]);
return diceToString;
}
private static void promptForReroll(int[] dice, Scanner inScanner) {
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
int selection = inScanner.nextInt();
while(selection != -1){
if(selection > 4 || selection < -1){
System.out.println("Erorr: Index must be between 0 and 4 (-1 to quit)!");
}
else{
dice[selection] = 0;
}
System.out.println("Your current dice: " + dice);
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
selection = inScanner.nextInt();
}
System.out.println("Keeping remaining die...");
}
private static boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
}
private static String getResult(int[] dice) {
getCounts(dice);
}
private static int[] getCounts(int[] dice) {
int[] count = new int[6];
int i = 0;
int j = 0;
while(i<5){
while(j<5){
if(dice[i] == (j+1)){
count[j]++;
i++;
}
else{
i++;
}
j++;
}
}
return count;
}
I have written out the coding, and I think for the most part it may be right, but I can't run it because it has errors on my promptForPlayAgain method, and my getResult method. I don't know why there are errors on them.
You aren't returning anything if the user's input isn't "Y" or "N". You need to add an else case:
private static Boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
else
{
//Do something here to handle bad input.
}
}
Ideally though, you should be doing some kind of formatting and preverification of the input, like forcing the input to upper case before comparing.
And on getResult, you aren't returning anything. Add a return before the body of the function. That won't fix it though, since the return type of getValue doesn't match getResult. You're trying to return a int array as a string.
In the future, please include the actual error messages they you receive.

Why Aren't My Cards Random?

I created this program in my quest to learn Java but every time I run it I get the same cards over and over again. I can't really find the problem, so why aren't my cards random? I don't really get what I'm missing, is my shuffle method incorrect?
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
System.out.println("Are you ready to play BlackJack?");
System.out.println();
playBlackjack();
System.out.println("Thanks for playing!");
}
static boolean playBlackjack() {
Deck deck;
Hand dealerHand;
Hand playerHand;
deck = new Deck();
dealerHand = new Hand();
playerHand = new Hand();
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
System.out.println();
if (dealerHand.getBlackjackValue() == 21) {
System.out.println("The dealer have the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("You have the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("The dealer has Blackjack! The dealer wins!");
return false;
}
if (playerHand.getBlackjackValue() == 21) {
System.out.println("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("User has the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("You have Blackjack. You win.");
return true;
}
while (true) {
// User decides whether to hit or stand
System.out.println();
System.out.println();
System.out.println("Your cards are:");
for ( int i = 0; i < playerHand.getCardCount(); i++ )
System.out.println(" " + playerHand.getCard(i));
System.out.println("The total of your hand is " + playerHand.getBlackjackValue());
System.out.println();
System.out.println("The dealer is showing the " + dealerHand.getCard(0));
System.out.println();
System.out.println("Do you hit(type 0) or stand(type 1)? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice != 0 && choice != 1){
System.out.println("0 or 1 must be inputted to continue ");}
while (choice != 0 && choice != 1);
if ( choice == 1 ) {
break;
}
else {
Card newCard = deck.dealCard();
playerHand.addCard(newCard);
System.out.println();
System.out.println("You hits and your card is the " + newCard);
System.out.println("The total of the hand is now " + playerHand.getBlackjackValue());
if (playerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("Fool of a Took! You went over 21 and busted!");
return false;
}
}
}
//User has stood at this point. Poor fool
System.out.println();
System.out.println("You stand. Wouldn't it be nice to sit sometime?");
System.out.println("The dealer's cards are "+ dealerHand.getCard(0) + " and the " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
System.out.println("The dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("The dealer busted! You win!");
return true;
}
}
System.out.println("The dealer's total is " + dealerHand.getBlackjackValue());
System.out.println();
if (playerHand.getBlackjackValue() == dealerHand.getBlackjackValue()) {
System.out.println("The house always wins on a tie. You lose :(");
return false;
}
else if (dealerHand.getBlackjackValue() >= playerHand.getBlackjackValue()) {
System.out.println("The dealer wins as he has " + dealerHand.getBlackjackValue()
+ " points to your " + playerHand.getBlackjackValue() + "!");
return false;
}
else {
System.out.println("You win because you had " + playerHand.getBlackjackValue()
+ " points while the dealer only had " + dealerHand.getBlackjackValue() + "!");
return true;
}
}
}
package blackjack;
public class Card {
private int suit;
private int rank;
public final static int SPADES = 0, // Codes for the 4 suits.
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;
public Card(int cRank, int cSuit) {
rank = cRank;
suit = cSuit;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public String getSuitString() {
// Return a String representing the card's suit.
// (If the card's suit is invalid, "??" is returned.)
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "I don't even know";
}
}
public String getRankString() {
switch ( rank ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "This is impossible!";
}
}
#Override
public String toString() {
return getRankString() + " of " + getSuitString();
}
}
package blackjack;
public class Deck {
private Card[] deck;
private int cardsUsed;
public Deck() {
deck = new Card[52];
int l = 0;
for ( int suit = 0; suit <= 3; suit++ ) {
for ( int value = 1; value <= 13; value++ ) {
deck[l] = new Card(value,suit);
l++;
}
}
cardsUsed = 0;
}
public void shuffle() {
for ( int i = 51; i > 0; i-- ) {
int rand = (int)(Math.random()*(i+1));
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
}
cardsUsed = 0;
}
public int cardsLeft() {
return 52 - cardsUsed;
}
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
}
package blackjack;
import java.util.*;
public class Hand {
private ArrayList hand;
public Hand() {
hand = new ArrayList();
}
public void clear() {
hand.clear();
}
public void addCard(Card c) {
if (c != null){
hand.add(c);
}
}
public void removeCard(Card c) {
hand.remove(c);
}
public void removeCard(int location) {
if (location >= 0 && location < hand.size()){
hand.remove(location);
}
}
public int getCardCount() {
return hand.size();
}
public Card getCard(int location) {
if (location >= 0 && location < hand.size()){
return (Card)hand.get(location);}
else{
return null;
}
}
public void sortBySuit() {
ArrayList newHand = new ArrayList();
while (hand.size() > 0) {
int pos = 0;
Card c = (Card)hand.get(0);
for (int i = 1; i < hand.size(); i++) {
Card c1 = (Card)hand.get(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit() && c1.getRank() < c.getRank()) ) {
pos = i;
c = c1;
}
}
Object remove = hand.remove(pos);
newHand.add(c);
}
hand = newHand;
}
public int getBlackjackValue() {
int val;
boolean ace;
int cards;
val = 0;
ace = false;
cards = getCardCount();
for ( int i = 0; i < cards; i++ ) {
Card card;
int cardVal;
card = getCard(i);
cardVal = card.getRank();
if (cardVal > 10) {
cardVal = 10;
}
if (cardVal == 1) {
ace = true;
}
val = val + cardVal;
}
if ( ace == true && val + 10 <= 21 ){
val = val + 10;
}
return val;
}
}
It's impossible to tell because you have not shown us the relevant code. However, if your results are not random, it's probably because Deck.dealCard() is not random.
Update
After reading the new code you posted. You are not shuffling your deck after you create it.
It's not random, because Deck::dealCard() is not random.
dealCard is quite strange: when a new Deck is created, cardsUsed is 0, yet you shuffle only if cardsUsed is 52.
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
I think you should move the call to shuffle to the constructor, right after constructing the deck.

Categories

Resources