2D array and detection if we fall off a map (JAVA) - java

I am printing simple map of numbers 1,2,3,4,5,6,7,8 (10/10) and everytime i type LEFT or RIGHT it doesnt tell me if im falling off the map but he is asking me if next YX is bigger than 9(collision from bottom and right) or its less than 0(collision from top and right) but instead he asks me what is in next cell( is it 1,2,3,4,5,6,7,8)
How the F*** do i check if he does not fall of the map?
Help please!!!!!!!
import java.util.Scanner;
public class Game {
static String dir = "";
static int player;
static int chest;
static int monster;
static int key;
static int tile;
static int wall;
static int keysFound = 0;
static int chestsOpened = 0;
static int chestsLeft = 3;
static int sword = 0;
static int angel;
static int pickaxe = 0;
static Scanner scan = new Scanner(System.in);
static int[][] map = new int[10][10];
static int x = map[0][0];
static int y = map[0][0];
static int playerPos = map[x][y];
static int life = 3;
static boolean isInGame;
static String NoTileFound = "trying to knock this wall is pointless try some other move";
static String FreeTile = "you move to a free tile";
public static void main(String[] args) {
MapCreator mapcreate = new MapCreator();
map = mapcreate.getMapcreated();
int isPlaying;
System.out.println(" Welcome to the game, kill monsters and open three chests to win");
System.out.println(" Gather a key to open the chest, collect 3 of theese to win! that's it!");
System.out.println(" Press 1 to play..anything else to exit!");
isPlaying = scan.nextInt();
if (isPlaying == 1) {
isInGame = true;
enterGame();
} else {
System.out.println("You missed out on a good game...");
System.exit(1);
}
}
public static void enterGame() {
System.out.println(
"Type, up, down, left, or right, to move. equipment to see what you have and exit to exit game");
while (isInGame) {
move();
}
}
public static void move() {
dir = scan.nextLine();
switch (dir) {
case "up":
entertileup();
break;
case "down":
entertiledown();
break;
case "left":
entertileright();
break;
case "right":
entertiledown();
break;
case "equipement":
System.out.println("you have " + life + " lifes, " + key + " keys and " + chestsOpened
+ " chests opened, keep searching solider!");
move();
break;
case "exit":
System.out.println("You missed out on a good game...");
System.exit(1);
}
ShowMap mapprint = new ShowMap();
mapprint.print(map);
}
public static void map() {
wall = 1;
tile = 2;
monster = 3;
chest = 4;
key = 5;
sword = 6;
player = 0;
angel = 7;
pickaxe = 8;
if (playerPos == tile) {
System.out.println(FreeTile);
}
if (playerPos == monster) {
monsterEncounter();
}
if (playerPos == chest) {
openChest();
}
if (playerPos == key) {
findKey();
}
if (playerPos == sword) {
findsword();
if (playerPos == angel) {
findangel();
}
if (playerPos == pickaxe) {
findpickaxe();
}
}
}
public static void entertileup() {
if (x + 1 > 9) {
System.out.println(NoTileFound);
move();
} else if (map[x + 1][y] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
x = x + 1;
playerPos = map[x][y];
map();
}
} else if (map[x + 1][y] == 2)
x = x + 1;
playerPos = map[x][y];
map();
}
public static void entertiledown() {
if (x - 1 < 0) {
System.out.println(NoTileFound);
move();
} else if (map[x - +1][y] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
x = x - 1;
playerPos = map[x][y];
map();
}
} else if (map[x - 1][y] == 2)
x = x - 1;
playerPos = map[x][y];
map();
}
public static void entertileright() {
if (y - 1 < 0) {
System.out.println(NoTileFound);
move();
} else if (map[x][y - 1] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
y = y - 1;
playerPos = map[x][y];
map();
}
} else if (map[x][y - 1] == 2)
y = y - 1;
playerPos = map[x][y];
map();
}
public static void entertileleft() {
if (y + 1 > 9) {
System.out.println(NoTileFound);
move();
} else if (map[x][y + 1] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
y = y + 1;
playerPos = map[x][y];
map();
}
} else if (map[x][y + 1] == 2)
y = y + 1;
playerPos = map[x][y];
map();
}
public static void findsword() {
System.out.println("You found a sword, monsters can't kill you! ");
sword = sword + 1;
map[x][y] = 0;
}
public static void findangel() {
System.out.println("You have found angel! what a mighty creature! He gives you a life");
life = life + 1;
map[x][y] = 0;
}
public static void findpickaxe() {
System.out.println("You have found a pickaxe Niceeee! you can destroy walls now! just simply walk over it");
pickaxe = pickaxe + 1;
map[x][y] = 0;
}
public static void monsterEncounter() {
if (sword == 0) {
if (life > 0) {
System.out.println("WOAH! A MONSTER! You kill him but you lose a life!");
life = life - 1;
System.out.println("You have: " + life + " life(s) left! Don't die out there!");
map[x][y] = 0;
} else {
System.out.println("You have: " + life + " , You encountered too many monsters. GAME OVER.");
System.exit(1);
}
} else {
System.out.println(" You killed a monster with mighty sword, no life loss, nice! ");
map[x][y] = 0;
}
}
public static void findKey() {
System.out.println("You found a key, nice!");
keysFound += 1;
map[x][y] = 2;
}
public static void openChest() {
System.out.println("Chest, nice!!");
if (keysFound >= 1) {
chestsOpened += 1;
int totalChestsFound = chestsLeft - chestsOpened;
chestsLeft -= 1;
System.out.println("You have opened a chest! You have " + totalChestsFound + " chests to go!");
map[x][y] = 2;
keysFound -= 1;
}
if (chestsLeft == 0) {
System.out.println("YOU WON! GOOD GAME SIR, GOOD GAME.");
System.exit(1);
} else {
System.out.println("No keys, no chests. Keep searching soldier.");
}
}
}

It looks like your map is a multidimensional array (0..7)(0..7), is it possible that what you're seeing is because you looking at a boundary of "9" and not "7"?
I also see that in your move() switch, case "left" looks at "entertileright()" and case "right" looks at "entertiledown()".

Related

Java Shut the Box

Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {
private int play;
private int die1;
private int die2;
private boolean[] table;
private final int high = 6;
private final int low = 1;
private int range;
public clacker()
{
range = high-low+1;
table = new boolean[13];
play = 0;
}
public void roll()
{
die1 = (int)(Math.random()*range+low);
die2 = (int)(Math.random()*range+low);
}
public void value(char ch)
{
if(ch == 'i' || ch == 'I')
{
table[die1] = true;
table[die2] = true;
displayBoard();
}
else if(ch == 'T' || ch == 't')
{
table[die1+die2] = true;
displayBoard();
}
else
{
roll();
}
}
public void displayBoard()
{
for(int i = 1; i<table.length; i++)
{
if(table[i] == false)
{
System.out.print(" " + i + " ");
}
else
{
System.out.print(" / ");
}
}
}
}
and for the test class:
public class clackerTest {
public static void main(String[] args) {
clacker oo = new clacker();
EasyReader kboard = new EasyReader();
System.out.println("Press anything to roll the dice. ");
char roll= kboard.readChar();
int dice1 = oo.roll();
int dice2 = oo.roll();
System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");
System.out.println("Cover Individual or Total: (enter i or t)");
char roll2 = kboard.readChar();
}
}
Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
return (int)(Math.random()*range+low);
}
And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();

How to have two different responses depending on the first string?

EDIT for a little bit more clearance:
I think what the code should do is: "If I put 0 as first on the "scanner", the text "you cant count the ones" should pop up.
But if I have typed some other numbers into scanner first, it should "break;" the program and print ONLY out the calculations that are at the bottom. Not the "you cant count the ones".
I seem to get one part of the two working, but not the both.
I've tried moving the if-sentences around, and moving System.out.println's around.
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int yksi = 0;
int numero = 0;
while (true) {
int luku = Integer.valueOf(lukija.nextLine());
if (luku == 0) {
System.out.println("you cant count the ones");
break;
}
if (luku == 1) {
yksi = yksi + 1;
} else if (luku != 0) {
numero = numero + 1;
}
}
System.out.println(1.0 * yksi / (numero + yksi));
}
I'm assuming you don't want to break when you first type 0 and only display the message "you cant count the ones". Then you can use a flag like this and put the break inside the else part,
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int yksi = 0;
int numero = 0;
boolean flag = true;
while (true) {
int luku = Integer.valueOf(lukija.nextLine());
if (luku == 0) {
if (flag) {
System.out.println("you cant count the ones");
} else {
break;
}
}
flag = false;
if (luku == 1) {
yksi = yksi + 1;
} else if (luku != 0) {
numero = numero + 1;
}
}
System.out.println(1.0 * yksi / (numero + yksi));
}

making java tic tac toe vs computer [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Thats my tictactoe game and i have this problem i cant find out...When i compile my programm
Welcome To Tic Tac Toe Professor Falken!
***Use Numbers 1-9 To Select A Square***
_1_|_2_|_3_|
_4_|_5_|_6_|
_7_|_8_|_9_|
You Go First!
___|___|___|
___|___|___|
___|___|___|
Player X, enter move (1 - 9):
10
INVALID MOVE: Enter number 1 - 9 only:
5
___|___|___|
___|_X_|___|
___|___|___|
Player O, enter move (1 - 9):
___|___|___|
___|_X_|_O_|
___|___|___|
Player X, enter move (1 - 9):
4
___|___|___|
_X_|_X_|_O_|
___|___|___|
Player O, enter move (1 - 9):
And stops there, i dont know why can anyone help me?
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private Scanner in;
private boardPiece[][] board = {{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()}};
private char turn = 'X';
private boolean win = false;
private int count = 0;
private Random random = new Random();
private int randomNumber = random.nextInt(9);
public static void main(String [] args)
{
int replay;
TicTacToe game = new TicTacToe();
game.in = new Scanner(System.in);
System.out.println("Welcome To Tic Tac Toe Professor Falken!");
System.out.println("***Use Numbers 1-9 To Select A Square***");
System.out.println("_1_|_2_|_3_|");
System.out.println("_4_|_5_|_6_|");
System.out.println("_7_|_8_|_9_|");
System.out.println(" n You Go First!");
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
while(replay != 2){
game.init();
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
}
game.in.close();
System.out.println("How about a nice game of chess :p");
}
public void play()
{
printBoard();
while(!win)
move();
}
public void printBoard()
{
for(int x=0; x<3; x++){
for(int y=0; y<3; y++){
System.out.print(board[x][y].piece);
}
System.out.println();
}
}
public void move()
{
int move = 0;
String valid = "";
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if(turn == 'O') {
move = randomNumber; }
else {
move = in.nextInt();
}
valid = checkMove(move);
while(valid != "ok")
{
if(turn == 'X') {
System.out.println("INVALID MOVE: "+ valid);
move = in.nextInt();
}
else {
move = randomNumber;
}
valid = checkMove(move);
}
count++;
board[(move-1)/3][(move-1)%3].piece = "_"+turn+"_|";
board[(move-1)/3][(move-1)%3].player = turn;
board[(move-1)/3][(move-1)%3].used = true;
printBoard();
if(count >= 5)
checkWin(move);
if(turn == 'X')
turn = 'O';
else
turn = 'X';
}
public String checkMove(int move)
{
if(move < 1 || move > 9)
return "Enter number 1 - 9 only: ";
else
if(board[(move-1)/3][(move-1)%3].used)
return "That move has been used. Enter another move (1 - 9): ";
else
return "ok";
}
public void checkWin(int move)
{
for(int x = 0; x<3; x++){ //Horizontal
if((board[x][0].used && board[x][1].used && board[x][2].used) &&
(board[x][0].player == board[x][1].player && board[x][0].player == board[x][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
for(int y = 0; y<3; y++)
{
if((board[0][y].used && board[1][y].used && board[2][y].used) &&
(board[0][y].player == board[1][y].player && board[0][y].player == board[2][y].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
if((board[0][0].used && board[1][1].used && board[2][2].used) &&
(board[0][0].player == board[1][1].player && board[0][0].player == board[2][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if((board[2][0].used && board[1][1].used && board[0][2].used) &&
(board[2][0].player == board[1][1].player && board[2][0].player == board[0][2].player))
{
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if(count==9){
System.out.println("Draw! Nobody Wins (ยด???`)");
win = true;
return;
}
}
public void init()
{
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
board[x][y] = new boardPiece();
}
}
turn = 'X';
win = false;
count = 0;
}
class boardPiece{
public String piece;
public char player;
public boolean used;
boardPiece(){
piece = "___|";
used = false;
}
}
}
I made a some changes in move and checkMove
public void move() {
int move = 0;
Boolean valid = false;
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if (turn == 'O') {
move = randomNumber;
} else {
move = in.nextInt();
}
valid = checkMove(move);
while (!valid) {
if (turn == 'X') {
move = in.nextInt();
} else {
move = random.nextInt(9);
}
valid = checkMove(move);
}
count++;
board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_|";
board[(move - 1) / 3][(move - 1) % 3].player = turn;
board[(move - 1) / 3][(move - 1) % 3].used = true;
printBoard();
if (count >= 5) {
checkWin(move);
}
if (turn == 'X') {
turn = 'O';
}else {
turn = 'X';
}
}
public Boolean checkMove(int move) {
if (move < 1 || move > 9) {
System.out.println("INVALID MOVE: Enter number 1 - 9 only: ");
return false;
}else if (board[(move - 1) / 3][(move - 1) % 3].used) {
System.out.println("INVALID MOVE: That move has been used. Enter another move (1 - 9): ");
return false;
}else {
return true;
}
}

Java Paper Rock Scissors program

Paper rock scissors java program.
Ok so the only problem I'm having now is the player's score doesn't update until the second loop around. Any suggestions?
Thanks again Radiodef for your help!!
Updated code below.......
import java.util.Scanner;
public class RPS_Game {
public static void main(String[] args) {
char r = 'R';
char p = 'P';
char s = 'S';
char player1 = 0;
char player2 = 0;
int player1Score = 0;
int player2Score = 0;
int playCount = 0;
Scanner scan = new Scanner(System.in);
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
int winner = winningPlayer(player1, player2);
if(winner == 0) {
System.out.print("\nIt's a tie. Nobody wins!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 1) {
System.out.print("\nPlayer 1 wins!!\n");
System.out.println("\nPlayer 1: " + player1Score++);
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 2) {
System.out.print("\nPlayer 2 wins!!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + player2Score++);
}
playCount++;
}
}
public static int winningPlayer(int player1, int player2) {
//Player 1 wins
int result = 0;
if(player1 == 'R' && player2 == 'S') {
result = 1;
}
else if(player1 == 'P' && player2 == 'R') {
result = 1;
}
else if(player1 == 'S' && player2 == 'P') {
result = 1;
}
//Player 2 wins
else if(player2 == 'R' && player1 == 'S') {
result = 2;
}
else if(player2 == 'P' && player1 == 'R') {
result = 2;
}
else if(player2 == 'S' && player1 == 'P') {
result = 2;
}
return result;
}
}
Well, it seems like first you just need to move the call in to the loop:
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
// recompute the winner each time
int winner = winningPlayer(player1, player2);
...
}
For keeping a score, you could just have a variable for each player:
int player1Score = 0;
int player2Score = 0;
while (...) {
...
if (winner == 1) {
++player1Score;
}
if (winner == 2) {
++player2Score;
}
}
Or you could do something fancier like use an array:
int[] scores = new int[3];
while (...) {
...
++scores[ winner ];
for (int i = 1; i < scores.length; ++i) {
System.out.printf("Player %d score is %d.\n", i, scores[i]);
}
}

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