I'm trying to make a simple BlackJack game driven by character input and I'm having a lot of problems in the later part it.
I commented the part that's giving me troubles, the rest doesn't seem to have errors and I did unit test it.
So, what did I do? I created a class that holds the cards drawn and manages them, table, player and dealer are both instances of table.
A table has max 5 cards(for simplicity), every card object comes from the Card class that has a method to add data to the card object.
The main class drives the program and the decisions are made with a character input from the keyboard, I get problems at that point.
import java.io.IOException;
class Table{
Card[] hand = new Card[5];
int counter = 1;
Table() {
for ( int i=0; i<hand.length; i++) {
hand[i]=new Card();
}
hand[0].GetCard();
}
void ReadCards(){
for(int i= 0;i<counter;i++ ) {
System.out.println("The card "+(i+1)+" is " + hand[i].name + " "+ hand[i].seed + "." );
}
}
void DrawCards() {
hand[counter].GetCard();
counter++;
}
boolean isOut() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
if(sum >21) {
return true;
}
}
return false;
}
int TheSum() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
return sum;
}
boolean isWIN(Table p2) {
int sum = 0;
int sump2 = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
for(int i= 0;i<p2.counter;i++ ) {
sump2 += p2.hand[i].value;
}
if (sum>sump2) {
return true;
}
else return false;
}
class Card {
public int value = 0;
public String name = "";
public String seed = "";
void GetCard(){
int positive = 0;
do {
positive = (int) (Math.random()*100) % 10;
}while(positive == 0 );
value = positive;
if(value<10) {
name = String.valueOf(value);
}
else {
positive = 0;
do {
positive = (int) (Math.random()*100) % 3;
}while(positive == 0 );
switch(positive) {
case 1:
name = "J";
break;
case 2:
name = "Q";
break;
case 3:
name ="K";
break;
}
}
positive = 0;
do {
positive = (int) (Math.random()*100) % 4;
}while(positive == 0 );
switch(positive) {
case 1:
seed = "CLUB";
break;
case 2:
seed = "DIAMOND";
break;
case 3:
seed ="SPADE";
break;
case 4:
seed ="HEART";
break;
}
}
}
}
public class BlackJack {
public static void main(String args[])throws IOException {
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char)System.in.read();
}while(flag != 'y' );
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
/*
flag = (char)System.in.read();
while(flag != 'n' ) {
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
flag = (char)System.in.read();
}
System.out.println("The dealer will draw");
while(dealer.TheSum()<18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
*/
System.out.println("WHO WON?");
if (player.isWIN(dealer)){
System.out.println("YOU WIN");
}
else System.out.println("YOU LOSE");
}
}
And yes, I'm not used to java.
Console screenshot of the output here!
Here is an example of fixing your looping issues, however there may be some issue with the game logic, which is out of the scope of this question.
public static void main(String args[]) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char) s.nextLine().charAt(0);
} while (flag != 'y');
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
while (true) {
flag = s.nextLine().charAt(0);
if (flag == 'n') {
break;
}
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
System.out.println("The dealer will draw");
while (dealer.TheSum() < 18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
System.out.println(String.format("The dealer has finished drawing. Dealers score %d. Your score %d", dealer.TheSum(), player.TheSum()));
}
System.out.println("WHO WON?");
if (player.isWIN(dealer)) {
System.out.println("YOU WIN");
} else {
System.out.println("YOU LOSE");
}
}
Output:
Welcome to the BlackJack's table! Press y to start!
y
DEALER
The card 1 is 8 CLUB.
PLAYER
The card 1 is 2 SPADE.
Do you want to draw a card? I'll draw until you'll press n
n
WHO WON?
YOU LOSE
Related
I created a dice game between the user and computer that loops 10 rounds - but if one of the game rounds is a tie - then it will ask if you want to play again and restart the game. I'm having a problem with the last part as the game iterates over at random times now. Any suggestions?
import java.util.Random;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("User vs. Computer Dice Game");
boolean Correct = false;
boolean Replay = false;
while(Replay == true) {
}
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for(int i =1; i<11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6)+1;
System.out.println("User rolled: "+usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6)+1;
System.out.println("Computer rolled: "+computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if(usernum == computernum) {
System.out.println("It\'s a tie!");
System.out.println("Do you want to play again? (Y/N) ");
System.out.println();
if (a.equalsIgnoreCase("N")){
Replay = true;
}
else {
Correct = false;
}
}
}
}
System.out.println();
}
}
}
Some notes:
You never set Correct=true.
Once inside the "while (Correct==false)" loop, you never test Replay.
There is no point in creating rand2. Just reuse rand1.
You have "for (int i=1;i<11;i++)" for the main loop.
Inside of that loop, and it's a tie, you ask if you want to play again, but there is nothing there to end the loop, so the inner for loop will continue to play out until you hit 11.
You might add a break statement when it's a tie to abort the for loop.
In fact, you're probably better off just aborting the loop and then asking the question again at the top of the while loop:
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for (int i = 1; i < 11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6) + 1;
System.out.println("User rolled: " + usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6) + 1;
System.out.println("Computer rolled: " + computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}
if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if (usernum == computernum) {
System.out.println("It's a tie!");
// Exit early from the for loop:
break;
}
}
}
else
{
Correct = true;
}
}
I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.
So in my blackjack program when each game ends the program asks you if you would to play again. My main problem right now is that when the new game is started the score counter just keeps adding the new score to the old score instead of resetting to 0. Im not really sure how to fix it. Here are the two classes where the problem is.
Player class:
public class Player{
private String name;
private Card[] hand; // from 2 - 5 cards allowed
private int cardCount,
chips;
public Player()
{
hand = new Card[5];
chips = 5;
cardCount = 0;
}
public Player(String n){
hand = new Card[5];
name = n;
chips = 5;
cardCount = 0;
}
public void acceptACard(Card c){
hand[cardCount] = new Card();
hand[cardCount] = c;
cardCount++;
}
public void showHand(int startCard)
{
for (int i = startCard; i < cardCount; i++){
System.out.print(hand[i] + "\t"); // displays one card from hand
}
}
public int calcScore(){
int cardScore =0;
int total = 0;
boolean hasAce = false;
for(int i=0; i < cardCount; i++){
cardScore = hand[i].getValue();
if (cardScore >=11 && cardScore <=13)
cardScore = 10;
else if (cardScore == 14){
cardScore = 11;
hasAce = true;
}
total += cardScore;}
if (total > 21 && hasAce == true)
total -= 10;
return total;
}
public void incrementChips(){
chips ++;
}
public void decrementChips(){
chips --;
}
public int getChips(){
return chips;
}
}
BlackJack class:
public class BlackJack {
private Player human,
computer;
private Deck deck = new Deck();
Scanner scan = new Scanner(System.in);
public BlackJack(){
human = new Player("");
computer = new Player ("");
}
public void playGame()
{
int cardTotal = 0;
String answer, answer2;
deck.shuffle();
do{
for ( int i = 0; i < 2; i++)
{
human.acceptACard(deck.dealACard());
computer.acceptACard(deck.dealACard());
}
System.out.print(" Human hand: ");
human.showHand(0);
System.out.print("\n Computer hand: ");
computer.showHand(1);
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if(human.calcScore() == 21 && computer.calcScore() < 21)
System.out.println("You win");
else if (computer.calcScore() == 21 && human.calcScore() < 21)
System.out.println("Computer wins!");
else if (computer.calcScore() == 21 && human.calcScore() == 21)
System.out.println("Tie!");
else if (human.calcScore() < 21)
do{
System.out.println("\nWould you like to hit or stay? Type hit or" +
" stay.");
answer = scan.nextLine();
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
}while(cardTotal < 4 && answer.equals("hit"));
determineWinner();
System.out.println("Would you like to play again? Enter yes or no: ");
answer = scan.nextLine();
}while(answer.equals("yes"));
reportGameStatus();
}
public void dealHand(){
int i = 2; int j =2;
human.acceptACard(deck.dealACard());
System.out.println("New card: ");
human.showHand(i++);
while(computer.calcScore() < 17){
computer.acceptACard(deck.dealACard());
System.out.println();
System.out.println("Computer's new card: ");
computer.showHand(j++);
}
}
public void determineWinner(){
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if (computer.calcScore() > human.calcScore() && computer.calcScore()<22){
System.out.println("Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (human.calcScore() > computer.calcScore() && human.calcScore()
<22){
System.out.println("You win!!");
human.incrementChips();
computer.decrementChips();
}
else if (human.calcScore() == computer.calcScore() )
System.out.println("Tie!");
else if (human.calcScore() > 21){
System.out.println("You bust! The Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (computer.calcScore() > 21){
System.out.println("The Computer busts! You win!");
computer.decrementChips();
human.incrementChips();
}
}
public void reportGameStatus(){
if(computer.getChips() > human.getChips())
System.out.println("Overall winner is the computer!");
else if(human.getChips() > computer.getChips())
System.out.println("You are the overall winner!");
}
}
Any help would be much appreciated.
I think here is your problem:
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
Instead of making new Objects you use the old ones and keep their inner state. That means your construktor is not used a second time and therefore your score, hand, chips are not resetted.
How about trying this:
if(answer.equals("hit"))
{
dealHand();
Player human = new Player();
human.calcScore();
Computer computer = new Coputer();
computer.calcScore();
cardTotal ++;
}
Also you have to make a new Deck everytime you start a new game:
Deck deck = new Deck();
Edit:
If you want to keep your chipCount place it in an Object wich will be initialiset in the constructor of your Blackjack class. After that call a function chipcount.setChipcount(chips); if you want to change the chipCount. Obvisoulsly your chipcount-object should have a getter getChipcounts() as well to get the actual chipCount.
It could look like this:
public BlackJack(){
human = new Player("");
computer = new Player ("");
ChipCount chipCount = new Chipcount(0);
}
here is how your object would be:
class ChipCount{
int chipCount;
public ChipCount(int startChips){
this.chipCount = startchips;
}
public void setChips(int chipsToAdd){
this.chipCount = this.chipcount + chipsToAdd;
}
public int getChips(){
return chipCount;
}
}
Before youre asking. Of course you could make two objects (ChipCountPlayer & ChipCountComputer). Also there is the possibility of giving setChips & getChips another argument like:
class ChipCount{
int chipCountPlayer;
int chipCountComp;
public ChipCount(int startChips){
this.chipCountPlayer = startchips;
this.chipCountComp = startchips;
}
public void setChips(int chipsToAdd, String player){
if(player.equals("player")){
this.chipCountPlayer = this.chipcountPlayer + chipsToAdd;
} else if (player.equals("computer")){
this.chipCountComp = this.chipcountComp + chipsToAdd;
}
}
public int getChips(String player){
if(player.equals("player")){
return chipCountPlayer;
} else if (player.equals("computer")){
return chipCountcomp;
}
}
}
that would be the other solution :P
PS: I am not fond of blackjack, does the computer even have chips? Anyway you could replace the comp with another player if you want to further extent your programm :D
I am writing a program in Java that is a classic BlackJack Game.
The rules are the same,and we make choices as players and the dealer(CPU) plays under some rules.
My code, that is beneath, makes 2 seperate stacks of Deck(s),one for Player and one for Dealer and each one draws from a different Deck but i want to make them both(Player and Dealer) draw from the same Deck(s).
Any suggestions/corrections on my Code ?
import java.util.Random;
import java.util.Scanner;
public class River
{
private int CardNumber;
private int BeginCards;
private int Decks;
private int[] PartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int[] BeginPartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int PickedCard;
private Random randomGenerator = new Random();
//Constructor without definition
public River()
{
CardNumber = 52;
BeginCards = 52;
}
//Constructor with definition
public River(int Decks)
{
CardNumber = Decks * 52;
BeginCards = CardNumber;
this.Decks = Decks;
//Initialize partial sum array for many decks of cards
for (int i=0; i<10; i++)
{
PartialSumArray[i] = PartialSumArray[i] * Decks;
BeginPartialSumArray[i] = PartialSumArray[i] * Decks;
}
System.out.println();
}
//Create random numbers
private int computeRandomSteps(int CardNumber)
{
//System.out.print("stin random , cardnumber is" + CardNumber);
int randomSteps = randomGenerator.nextInt(CardNumber-1);
return randomSteps;
}
public int nextCard()
{
int steps = computeRandomSteps(CardNumber);
int position=0;
for (int i=0; i<CardNumber; i++)
{
if (steps<= PartialSumArray[i])
{
position = i+1;
break;
}
}
CardNumber--;
return position;
}
public int start()
{
int ShuffleLimit;
PickedCard = nextCard();
System.out.println("Picked card is :" + PickedCard);
int HelpVariable = PickedCard-1;
for (int i=0; i<10; i++)
{
if (i >= HelpVariable)
{
PartialSumArray[HelpVariable] = PartialSumArray[i]-1;
HelpVariable++;
}
}
ShuffleLimit = BeginCards/4;
if (CardNumber<ShuffleLimit)
{
for (int i=0; i<9; i++)
{
BeginPartialSumArray[i] = BeginPartialSumArray[i] * Decks;
}
}
return PickedCard;
}
public int ReturnCardNumber()
{
System.out.println("return cardnumber is " + CardNumber);
return CardNumber;
}
}
class Hand
{
private int points;
private int SumPoints=0;
private boolean Ace = true;
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
public int getPoints()
{
points = myRiver.start();
if (points == 1 && Ace)
{
System.out.println("It is an Ace. Do you want to count 1 or 11?");
points = input.nextInt();
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
public int getPointsDealer()
{
points = myRiver.start();
if (points == 1 && Ace)
{
if (SumPoints + 11 > 21)
{
points = 1;
}
else
{
points = 11;
}
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
}
class Player
{
private int points;
private double account=0;
private double bet;
private boolean WinOrLose;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
public double placeBet()
{
System.out.println("How much do you want to bet?");
bet = input1.nextDouble();
return bet;
}
public double profit(boolean WinOrLose)
{
if (WinOrLose)
{
account += bet;
return account;
}
else
{
account -= bet;
return account;
}
}
public int play(River other)
{
Hand myHand = new Hand();
bet = placeBet();
points = myHand.getPoints();
boolean end = true;
String Choice;
while (end)
{
System.out.println("Make a choice");
Choice = input2.nextLine();
switch(Choice)
{
case "DoubleBet":
bet = bet *2;
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
else
{
System.out.println("Your points are :" + points);
end = false;
break;
}
case "stop":
System.out.println("Your points are :" + points);
end = false;
break;
case "Hit":
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
break;
default:
System.out.println("That is not a choice.");
end = false;
break;
}
}
return points;
}
}
class BlackJack
{
public static void main(String args[])
{
int SumPointsPlayer;
int SumPointsDealer;
boolean WinOrLose = true;
double account;
int Decks;
int BeginCards;
int ThisMomentCards;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("How many decks do you want to begin with?");
Decks = input1.nextInt();
River myRiver = new River(Decks);
Player myPlayer = new Player();
//Calculate the cards we have when the game starts
BeginCards = 52 * Decks;
System.out.println("Do you want to start the game? Yes or No.");
String Repeat;
Repeat = input2.nextLine();
while (Repeat.equals("Yes"))
{
ThisMomentCards = myRiver.ReturnCardNumber();
System.out.println("Cards are : " + ThisMomentCards);
//Player's points for 1 round
SumPointsPlayer = myPlayer.play(myRiver);
//If player catches 21 he wins instantly
if(SumPointsPlayer == 21)
{
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//If player catches >21 he loses instantly
else if(SumPointsPlayer > 21)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Compare the hand of player and dealer and the bigger wins
else
{
//Dealer's points for 1 round
SumPointsDealer = playDealer(myRiver);
//If dealer catches >21 he loses instantly
if(SumPointsDealer>21)
{
System.out.println("Player wins!");
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Hand of player bigger than the hand of the dealer , player wins
else if (SumPointsPlayer>SumPointsDealer)
{
WinOrLose = true;
account = myPlayer.profit(WinOrLose);
System.out.println("Player wins. Your account has :" + account + "dollars!");
}
//Hand of player smaller than the hand of the dealer , dealer wins
else if (SumPointsPlayer<SumPointsDealer)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Player lost. Your account has :" + account + "dollars!");
}
//Hand of player is equal with the hand of the dealer , it is tie
else
{
System.out.println("Player and Dealer are tie!!");
}
}
System.out.println("Do you want to continue the game? Yes or No.");
Repeat = input2.nextLine();
}
}
public static int playDealer(River other)
{
boolean bountry = true;
System.out.println("Dealer plays :");
Hand myHand = new Hand();
int SumPointsDealer = myHand.getPointsDealer();
while (bountry)
{
if (SumPointsDealer<17)
{
SumPointsDealer = myHand.getPointsDealer();
}
else if (SumPointsDealer>21)
{
System.out.println("Dealer burned!");
bountry = false;
}
else
{
bountry = false;
}
}
return SumPointsDealer;
}
}
Some Clarifications:
1) The way we draw randomly a card is based on a strange way but this is not the problem its ok the way the program Does draw randomly cards from the Decks
2) Another problem that i noticed is that in class Hand the code that i have in // is not working as it doesnt allow me to have a System.out.println()
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
I wanted to do this so that i will say with how many Decks the user wants to play
You can do better and easier of code is oriented into objects.
i.e. Collections.shuffle(Deck) replaces that whole random conundrum
where Deck is your created Object made of such attributes as LinkedList and a counter[deck value]
hope that helps.
remove object Card from linked list of main deck and move it into the deck of a player. and yes, you can create as many decks as you want that way.
object Card has attributes Value and Suit.
I am doing a TicTacToe Program, the only missing part is to have the user to choose whether to quit the game or to replay. I can't find a way to "return" to the gaming.
import java.io.*;
public class Expierment
{
static char c1 [] = new char[10];
static char c2 [] = new char[10];
static char c3 [] = new char[10];
static char p1;
static char p2;
static boolean gameOver = false;
public static void main(String args[])
{
int counter = 0;
int p1Wins = 0;
int p2Wins = 0;
int r1 = 0;
int r2 = 0;
int r3 = 0;
int r4 = 0;
int r5 = 0;
int r6 = 0;
int r7 = 0;
int r8 = 0;
int r9 = 0;
int pick1 = 0;
int pick2 = 0;
int pick3 = 0;
int pick4 = 0;
int pick5 = 0;
int pick6 = 0;
int pick7 = 0;
int pick8 = 0;
int pick9 = 0;
char turn = 'X';
int choice = menu();
switch(choice)
{
case 1:
System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.") ;
case 2:
gameOver = false;
break;
case 3:
System.out.println("\nSee you next time !!");
return;
default:
System.out.println("\nYou hit the wrong key......\n");
return;
}//end of switch
System.out.println("\nPlayer 1 initials ?");
String n1 = GCS();
p1 = n1.charAt(0);
System.out.println("\nPlayer 2 initials ?");
String n2 = GCS();
p2 = n2.charAt(0);
c1[2]='1';
c2[2]='2';
c3[2]='3';
c1[1]='4';
c2[1]='5';
c3[1]='6';
c1[0]='7';
c2[0]='8';
c3[0]='9';
printBoard ();
while(gameOver!=true)
{
System.out.println("Which spot ?");
int pick = Integer. parseInt(GCS());
switch (pick)
{
case 1:
if (r1<1)
{
c1[2] = turn;
r1++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 2:
if (r2<1)
{
c2[2] = turn;
r2++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 3:
if (r3<1)
{
c3[2] = turn;
r3++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 4:
if (r4<1)
{
c1[1] = turn;
r4++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 5:
if (r5<1)
{
c2[1] = turn;
r5++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 6:
if (r6<1)
{
c3[1] = turn;
r6++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 7:
if (r7<1)
{
c1[0] = turn;
r7++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 8:
if (r8<1)
{
c2[0] = turn;
r8++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 9:
if (r9<1)
{
c3[0] = turn;
r9++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
default:
System.out.println("Seriously?! Pick a possible spot.\n");
continue;
}//end of switch
if (turn=='X') turn = 'O';
else turn = 'X';
printBoard();
if (checkWinner())
{
while(gameOver==true)
{
int Echoice = EGM();
switch(Echoice)
{
case 1:
System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.") ;
case 2:
gameOver = false;
menu();
break;
case 3:
System.out.println("\nSee you next time !!");
return;
default:
System.out.println("\nYou hit the wrong key......\n");
return;
}//end of switch
}//end of while true
return;
}
counter ++;
if (counter==9)
{
System.out.println("\n\nYou tied.\n");
return;
}
}//end of while not true
}//end of main
public static boolean checkWinner()
{
for (int k=0; k<2; k++)
{
if ((c1[k]!=' ')&&(c1[k]==c2[k])&&(c1[k]==c3[k]))
{
System.out.println("\nYo " + c1[k] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 1-3 horizontally
}//end of horizontal check
for (int m=0; m<2; m++)
{
if((c1[m]!=' ')&&(c1[m]==c1[m+1])&&(c1[m+1]==c1[m+2])&&(c1[m]==c1[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 1 vertically
if((c2[m]!=' ')&&(c2[m]==c2[m+1])&&(c2[m+1]==c2[m+2])&&(c2[m]==c2[m+2]))
{
System.out.println("\nYo " + c2[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 2 vertically
if((c3[m]!=' ')&&(c3[m]==c3[m+1])&&(c3[m+1]==c3[m+2])&&(c3[m]==c1[m+2]))
{
System.out.println("\nYo " + c3[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 3 vertically
if ((c1[m]!=' ')&&(c1[m]==c2[m+1])&&(c1[m]==c3[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks upward diagonal
if ((c3[m]!=' ')&&(c3[m]==c2[m+1])&&(c3[m]==c1[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}
}//end of vertical check
return false;
}//end of checkWinner
public static void printBoard()
{
System.out.println("_______");
for (int j = 2; j > -1; j--)
{
System.out.println("|" + c1[j] + "|" + c2[j] + "|" + c3[j] + "|");
System.out.println("-------");
}
}//end of printBoard
public static int menu()
{
System.out.println("Tic-Tac-Toe ~ Main Menu\n\n1. Instructions\n2. Play a 1 player game"+"\n3. Exit\n");
int selection = Integer.parseInt(GCS());
return selection;
}//end of menu
public static int EGM()
{
System.out.println("Tic-Tac-Toe ~ End of Game Menu\n\n1. Instructions\n2. Play again"+"\n3. Exit\n");
int Eselection = Integer.parseInt(GCS());
return Eselection;
}
public static String GCS()
{
int noMoreInput=-1;
char enterKeyHit='\n';
int InputChar;
StringBuffer InputBuffer = new StringBuffer(100);
try
{
InputChar=System.in.read();
while(InputChar != noMoreInput)
{
if((char)InputChar !=enterKeyHit)
{
InputBuffer.append((char)InputChar);
}
else
{
InputBuffer.setLength(InputBuffer.length()-1);
break;
}
InputChar=System.in.read();
}
}
catch (IOException IOX)
{
System.err.println(IOX);
}
return InputBuffer.toString();
}//end of GCS
}//end of public class
You really should get some of that code out of the main function.
Specifically, I'd put the whole game loop in a separate function, maybe called playGame(), which contains the logic for playing the game, checking winner, etc., and either returns the winner or just prints the winner and returns void.
Then the main function could put a call to playGame() in a loop, and at the end of the loop, ask the user if s/he wants to play again.
In general, you want each function to do one logical task. You've done well with moving checkWinner out, now do the same with some of the other code.
If you need help on the "asking the user about playing again", leave a comment and I'll make an edit to address that.
quick and dirty pseudo-code - not modular
do {
//everything in your main goes here
.
.
.
playAgain = prompt the user
} while(playAgain);
With the current program layout, there is no "clean" way to accomplish that. Here are some constructive criticism :
Your main method should only be a bootstrapper
You should only initialize your program in your main method. Consequently, try to have 1 method doing only 1 thing. You're design now has the game menu and game main loop inside the same method.
Your game loop could look like this:
while still playing
read input from user
if game is active
process game input
update game
else
process menu input
update menu
This way, you only need to swith the game is active state for the menu or the game. Etc.
Do not reinvent the wheel
Your GCS method is way too complicated, just replace it with :
Scanner scanner = new Scanner(); // put this somewhere at the class level (so it is reusable)
...
String input = scanner.nextLine(); // put this somewhere in a method reading an input
Variable abuse
Instead of initializing many variables, perhaps (like other have suggested) you could use arrays, or more specifically a 2-dimensional array.
int grid[][] = new int[3][3];
// grid[0][0] points to the top-left cell, grid[2][2] points to the bottom right one
Or you could use a single int to store everything; represent your grid as a bit array
int grid = 0; // empty grid
...
// set player move
grid |= (1 << (y*3)+x) << PLAYER_OFFSET; // PLAYER_OFFSET: 0=player 1, 16=player 2
// reset (clear) player move
grid &= ~((1 << (y*3)+x) << PLAYER_OFFSET); // ...
// check if player move is set
boolean isSet = (grid >> ((1 << (y*3)+x) << PLAYER_OFFSET)) && 1; // ...
Why are bit arrays cool? Because to check if a player wins, you don't need fancy for..loop and other complicated algorithms, just validate against a winning pattern... :
int pattern = 273; // test for diagonal from [0,0] to [2,2], or bits "100 010 001"
boolean isWinning = (grid && (pattern << PLAYER_OFFSET)) != 0;
That's it!
Also, using 0 to 9 may be good to identify the grid cell, however as input value is not that intuitive for a player. Many games (chess, checkers, LOA, etc.) and applications (Excel, Calc, etc.), for example, are using the Algebraic chess notation system. Converting the notation in x and y is very simple. For example :
boolean cellPlayed = false;
while (!cellPlayed) {
String cellStr = scanner.readLine().toLower(); // ex: "b2" for the center cell
try {
int gridx = cellStr.charAt(0) - 'a'; // ex: for "b2" should return 1
int gridy = cellStr.charAt(1) - '1'; // ex: for "b2" should return 1
grid(gridx][gridy] = playerValue; // 1 for "player 1" and 2 for "player 2"
cellPlayed = true;
} catch (Exception e) {
System.out.println("Error! Invalid input");
}
}
Don't feel discouraged! We all start somewhere! :)
Even dirtier than the do-while method. Will eventually cause stack-overflow.
//your current main method
boolean playAgain = prompt the user
if(playAgain){
main(args);
}
Things would be a lot more clear with a more concise main method. The really quick and dirty way would be to copy everything in your main method into a new method and just call that method from the main and when the user chooses to start a new game.