Basic Tic Tac Toe in java - java

I am trying to make a simple tic tac toe Game in Java and I'm almost done but my program doesn't declare a winner and doesn't declare if the game is a draw or not even when in my code I told it to declare a winner.
Here is my code:
import java.util.*;
public class TicTacToe {
/**
* #param args the command line arguments
*/
public static int row, colm;
public static char board[][] = new char [3][4];
public static Scanner console = new Scanner(System.in);
public static char turn = 'X';
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 4; j++){
board[i][j] = '_';
}
}
board();
play();
winner(row,colm);
}
public static void board() {
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 4; j++) {
if(j == 0) {
System.out.print("|");
} else {
System.out.print(board[i][j]+"|");
}
}
System.out.println();
}
}
public static void play() {
boolean playing = true;
while(playing) {
row = console.nextInt();
colm = console.nextInt();
board[row][colm] = turn;
if(winner(row,colm)) {
playing = false;
System.out.print("you win");
}
board();
if(turn == 'X') {
System.out.println("Player 2 your O");
turn = 'O';
} else
turn='X';
}
}
public static boolean winner(int move1, int move2) {
if(board[0][move2] == board[1][move2] && board[0][move2] == board[2][move2])
return true;
if(board[move1][0] == board[move1][1] && board[move1][0] == board[move1][2])
return true;
if(board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_')
return true;
if(board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_')
return true;
return false;
}

If it is done like that, then turn will have the wrong value after someone has won and you want to display it in main, here are the corrections:
public static void main(String[] args) {
...
board();
play();
// remove winner(row,colm); it isn't doing anything here
// turn has the right value of the winner here if play() is modified
}
public static void play() {
// remove boolean playing = true; it is not needed
for (;;) { // I call it the 'forever', but you can also write while(true)
...
board[row][colm] = turn;
board(); // move up unless you don't want to display the board on wins
if (winner(row,colm)) {
System.out.print(turn + " you win");
return; // (or break) <-- otherwise turn has the wrong value in main
}
...
}
}

Related

Tic tac toe game loop stops when it is a draw - Java

According to the requirements from my learning platform works fine apart from when the input command is "start easy easy" and the result is draw program doesn't stop and nothing happens after that and I have to force end the program. In all other cases program continues to run unless user types in "exit". Please help and also if you can suggest how to improve my code and in terms of OOP that will be great. Thank you.
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class Main {
public final static Scanner scan = new Scanner(System.in);
public static Random random = new Random();
public static char[][] gameBoard;
public static String level = "";
public static void main(String[] args) {
// write your code here
menu();
}
public static String[] getParams() {
String[] params = scan.nextLine().split(" ");
return params;
}
public static void menu() {
while (true) {
System.out.println("Input command: ");
String[] params = getParams();
if (params.length == 3) {
if ("start".equals(params[0])) {
level = params[1].equals("easy") ? params[1] : params[2];
start(params[1], params[2]);
continue;
}
} else if (params.length == 1) {
if ("exit".equals(params[0])) {
break;
} else {
System.out.println("Bad parameters!");
continue;
}
} else {
System.out.println("Bad parameters!");
continue;
}
break;
}
}
public static void start(String str1, String str2) {
gameBoard = to2dArray("_________");
drawBoard(gameBoard);
char player1 = 'X';
char player2 = 'O';
if ("user".equals(str1)) {
while (!gameFinished(gameBoard)) {
drawBoard(playerMove(gameBoard, player1));
gameState(gameBoard);
drawBoard(computerMove(gameBoard, player2));
gameState(gameBoard);
}
} else if ("user".equals(str2)) {
while (!gameFinished(gameBoard)) {
gameState(computerMove(gameBoard, player2));
drawBoard(gameBoard);
gameState(playerMove(gameBoard, player1));
drawBoard(gameBoard);
}
} else if ("user".equals(str1) && "user".equals(str2)) {
while (!gameFinished(gameBoard)) {
drawBoard(playerMove(gameBoard, player1));
gameState(gameBoard);
drawBoard(playerMove(gameBoard, player2));
gameState(gameBoard);
}
} else {
while (!gameFinished(gameBoard)) {
drawBoard(computerMove(gameBoard, player1));
gameState(gameBoard);
drawBoard(computerMove(gameBoard, player2));
gameState(gameBoard);
}
}
}//startGame method
public static int[] getRandomNumber() {
int[] computerCoords = new int[2];
while (true) {
int a = random.nextInt((3 - 1) + 1) + 1;
int b = random.nextInt((3 - 1) + 1) + 1;
if (gameBoard[a - 1][b - 1] == 'X' || gameBoard[a - 1][b - 1] == 'O') {
continue;
} else {
computerCoords[0] = a;
computerCoords[1] = b;
break;
}
}
return computerCoords;
}
public static char[][] computerMove(char[][] gameBoard, char computer) {
int[] arr = getRandomNumber();
int row = arr[0] - 1;
int col = arr[1] - 1;
if (!gameFinished(gameBoard)) {
System.out.println("Making move level \"" + level + "\"");
gameBoard[row][col] = computer;
}
return gameBoard;
}
public static char[][] playerMove(char[][] gameBoard, char player) {
int index = 0;
int row, column;
while (true) {
System.out.println("Enter the coordinates: ");
String[] coordinates = scan.nextLine().split(" ");
try {
row = Integer.parseInt(coordinates[0]);
column = Integer.parseInt(coordinates[1]);
if ((row < 1 || column < 1) || (row > 3 || column > 3)) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
}
row -= 1;
column -= 1;
if (gameBoard[row][column] != '_') {
System.out.println("This cell is occupied! Choose another one!");
continue;
}
gameBoard[row][column] = player;
return gameBoard;
} catch (NumberFormatException e) {
System.out.println("You should enter numbers!");
continue;
}
}//while loop ends here
}// playerMove() ends
public static char[][] to2dArray(String s) {
char[][] twoDArray = new char[3][3];
int index = 0;
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[i].length; j++) {
twoDArray[i][j] = s.charAt(index);
index++;
}
}
return twoDArray;
}// to2dArray method
public static void drawBoard(char[][] arr) {
System.out.println("---------");
for (int i = 0; i < arr.length; i++) {
System.out.print("| ");
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == '_') {
System.out.print(" " + " ");
} else {
System.out.print(arr[i][j] + " ");
}
}
System.out.println("|");
}
System.out.println("---------");
}//end drawBoard method
public static boolean xWon (char[][] gameBoard) {
char[] xWins = {'X', 'X', 'X'};
char[][] winningCombos = {
{gameBoard[0][0], gameBoard[0][1], gameBoard[0][2]}, //horizontal
{gameBoard[1][0], gameBoard[1][1], gameBoard[1][2]}, //horizontal
{gameBoard[2][0], gameBoard[2][1], gameBoard[2][2]}, //horizontal
{gameBoard[0][0], gameBoard[1][0], gameBoard[2][0]}, //vertical
{gameBoard[0][1], gameBoard[1][1], gameBoard[2][1]}, //vertical
{gameBoard[0][2], gameBoard[1][2], gameBoard[2][2]}, //vertical
{gameBoard[0][0], gameBoard[1][1], gameBoard[2][2]}, //diagonal
{gameBoard[0][2], gameBoard[1][1], gameBoard[2][0]} //diagonal
};
for (char[] charArray : winningCombos) {
if (Arrays.equals(xWins, charArray)) {
return true;
}
}
return false;
}// end xWon method
public static boolean oWon (char[][] gameBoard) {
char[] oWins = {'O', 'O', 'O'};
char[][] winningCombos = {
{gameBoard[0][0], gameBoard[0][1], gameBoard[0][2]}, //horizontal
{gameBoard[1][0], gameBoard[1][1], gameBoard[1][2]}, //horizontal
{gameBoard[2][0], gameBoard[2][1], gameBoard[2][2]}, //horizontal
{gameBoard[0][0], gameBoard[1][0], gameBoard[2][0]}, //vertical
{gameBoard[0][1], gameBoard[1][1], gameBoard[2][1]}, //vertical
{gameBoard[0][2], gameBoard[1][2], gameBoard[2][2]}, //vertical
{gameBoard[0][0], gameBoard[1][1], gameBoard[2][2]}, //diagonal
{gameBoard[0][2], gameBoard[1][1], gameBoard[2][0]} //diagonal
};
for (char[] charArray : winningCombos) {
if (Arrays.equals(oWins, charArray)) {
return true;
}
}
return false;
}// end oWon method
public static boolean hasEmptyCells(char[][] gameBoard) {
for (char[] arr : gameBoard) {
for (char ch : arr) {
if (ch == '_') {
return true;
}
}
}
return false;
} //end of hasEmptyCells method;
public static boolean gameFinished(char[][] gameBoard) {
if (xWon(gameBoard) || oWon(gameBoard) || draw(gameBoard)) {
return true;
}
return false;
} //end of gameFinished method.
public static boolean draw(char[][] gameBoard) {
if(!xWon(gameBoard) && !oWon(gameBoard) && !hasEmptyCells(gameBoard)) {
return true;
}
return false;
}
public static char[][] gameState(char[][] gameBoard) {
if (xWon(gameBoard)) {
System.out.println("X wins");
return gameBoard;
} else if (oWon(gameBoard)) {
System.out.println("O wins");
return gameBoard;
} else if (draw(gameBoard)) {
System.out.println("Draw");
return gameBoard;
}
return gameBoard;
}//gameState method
}// Main class
The draw happens halfway into this:
while (!gameFinished(gameBoard)) {
drawBoard(computerMove(gameBoard, player1));
gameState(gameBoard);
// Result is now Draw
drawBoard(computerMove(gameBoard, player2));
gameState(gameBoard);
}
You try to generate another computerMove after the first one, but that is impossible, because the board is already full.
A possible solution woud be to check gameFinished before attempting another move

tic tac toe java user vs computer

I am writing a tic tac toe game for my class. Everything is working but I am unable to figure out how to make my computer player choose only spaces that are available. My code is glitching and allowing the computer to choose either the other players spaces or not playing at all. Any help will be appreciated.
import java.util.Random;
import java.util.Scanner;
public class TicTacToe1 {
public static void main(String[] args) {
welcome();
initializeBoard();
printBoard();
while ((!checkWin()) && (!checkDraw())) {
playerMove();
printBoard();
System.out.println();
computerMove();
printBoard();
}
System.out.println();
if (checkWin() == true) {
System.out.println("The winner is " + currentTurn);
}
if (checkDraw() == true) {
System.out.println("Draw");
}
}
private static String[][] board = new String[3][3];
private static int row, column;
public static Scanner scan = new Scanner(System.in);
public static String currentTurn = "X";
// public static String computerTurn = "O";
public static String turn() {
if (currentTurn == "X") {
currentTurn = "O";
} else {
currentTurn = "X";
}
return currentTurn;
}
private static void welcome() {
System.out.println("Tic Tac Toe");
System.out.println("Please enter your coordinates for your location row (1-3) column (1-3):");
}
public static void initializeBoard() { // initialize tic tac toe
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = "-";
}
}
}
public static void printBoard() {
for (int i = 0; i < board.length; i++) {
System.out.println();
for (int j = 0; j < board.length; j++) {
if (j == 0) {
System.out.print("| ");
}
System.out.print(board[i][j] + " | ");
}
}
}
public static void playerMove() {
System.out.println();
System.out.println("Your Move: ");
row = scan.nextInt() - 1;
column = scan.nextInt() - 1;
if (board[row][column] == "-") {
board[row][column] = turn();
} else {
System.out.println("Invalid entry. Please go again");
row = scan.nextInt() - 1;
column = scan.nextInt() - 1;
board[row][column] = turn();
}
}
// public static void computerMove() {
// Random computerMove = new Random();
// row = computerMove.nextInt(3);
// column = computerMove.nextInt(3);
// if (board[row][column] == "-") {
// board[row][column] = turn();
// } else {
// }
// }
public static void computerMove() {
Random computerMove = new Random();
row = computerMove.nextInt(3);
column = computerMove.nextInt(3);
while (board[row][column] != "-") {
// Random computerMove = new Random();
// row = computerMove.nextInt(3);
// column = computerMove.nextInt(3);
if (board[row][column] == "-") {
board[row][column] = turn();
} else {
row = computerMove.nextInt(3);
column = computerMove.nextInt(3);
board[row][column] = turn();
}
}
}
public static boolean checkWin() {
return (checkDiagonalWin() || checkHorizontalWin() || checkVerticalWin());
}
public static boolean checkDiagonalWin() {
if ((board[0][0] == board[1][1]) && (board[0][0] == board[2][2]) && (board[1][1] != "-")) {
return true;
}
if ((board[0][2] == board[1][1]) && (board[0][2] == board[2][0]) && (board[1][1] != "-")) {
return true;
}
return false;
}
public static boolean checkHorizontalWin() {
// for (int i = 0; i < board.length; i++) {
if ((board[0][0] == board[0][1]) && (board[0][0] == board[0][2]) && (board[0][0] != "-")) {
return true;
}
if ((board[1][0] == board[1][1]) && (board[1][0] == board[1][2]) && (board[1][0] != "-")) {
return true;
}
if ((board[2][0] == board[2][1]) && (board[2][0] == board[2][2]) && (board[2][0] != "-")) {
return true;
}
// }
return false;
}
public static boolean checkVerticalWin() {
// for (int j = 0; j < board.length; j++) {
if ((board[0][0] == board[1][0]) && (board[0][0] == board[2][0]) && (board[0][0] != "-")) {
return true;
}
if ((board[0][1] == board[1][1]) && (board[0][1] == board[2][1]) && (board[0][1] != "-")) {
return true;
}
if ((board[0][2] == board[1][2]) && (board[0][2] == board[2][2]) && (board[0][2] != "-")) {
return true;
}
// }
return false;
}
public static boolean checkDraw() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == "-") {
return false;
}
}
}
return true;
}
}
The issue was in your computerMove logic.
public static void computerMove() {
Random computerMove = new Random();
row = computerMove.nextInt(3);
column = computerMove.nextInt(3);
while (board[row][column] != "-") {
row = computerMove.nextInt(3);
column = computerMove.nextInt(3);
}
board[row][column] = turn();
}
This should work for you, just copy paste this in place of your computerMove.
Now as to why your code didn't work:-
Your code:
while (board[row][column] != "-") {
if (board[row][column] == "-") {
board[row][column] = turn();
} else {
row = computerMove.nextInt(3);
column = computerMove.nextInt(3);
board[row][column] = turn();
}
}
The while loop looks at the position and sees that there is no '-', thus runs. Then inside your while loop you have a if statement which checks to see whether you have '-' at that position. That can never be true, because our while loop wouldn't run otherwise.
The best idea is to let your code keep changing the row and columns until you get a position with '-', and use your while loop to do that. As soon as you get the '-', your while loop won't run anymore anyways, so you can just set the board[row][columns] = turn() just outside the while loop, and your code will work fine.
P.S. Took a lot of willpower to not make a machines are uprising reference to your
My code is glitching and allowing the computer to choose either the other players spaces or not playing at all
Have fun with your program :)
~HelpfulStackoverflowCommunity

make players change after certain time in java

I want to add the following functionality in a tictactoe game: if a player is on turn but he/she doesn't do anything for a certain time (10 seconds), than it's the another player's turn.
In the "GameHub" class (extends a Server class for creating only one game) I have the inner class "GameState", which maintains the current state of the game and passes it as a message to the server (and then it is forwarded to all clients/players).
public class GameHub extends Server {
private GameState state;
public GameHub(int port) throws IOException {
super(port);
state = new GameState();
setAutoreset(true);
}
protected void messageReceived(int playerID, Object message) {
state.applyMessage(playerID, message);
sendToAll(state);
}
protected void playerConnected(int playerID) {
if (getPlayerList().length == 2) {
shutdownServerSocket();
state.startFirstGame();
sendToAll(state);
}
}
protected void playerDisconnected(int playerID) {
state.playerDisconnected = true;
sendToAll(state);
}
public static class GameState implements Serializable {
public boolean playerDisconnected;
public char[][] board;
public boolean gameInProgress;
public int playerPlayingX;
public int playerPlayingO;
public int currentPlayer;
public boolean gameEndedInTie;
public int winner;
public void applyMessage(int sender, Object message) {
if (gameInProgress && message instanceof int[] && sender == currentPlayer) {
int[] move = (int[]) message;
if (move == null || move.length != 2) {
return;
}
int row = move[0];
int col = move[1];
if (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ') {
return;
}
board[row][col] = (currentPlayer == playerPlayingX) ? 'X' : 'O';
if (winner()) {
gameInProgress = false;
winner = currentPlayer;
} else if (tie()) {
gameInProgress = false;
gameEndedInTie = true;
}
else {
currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
}
} else if (!gameInProgress && message.equals("newgame")) {
startGame();
}
}
void startFirstGame() {
startGame();
}
private void startGame() {
board = new char[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
int xPlr = (Math.random() < 0.5) ? 1 : 2;
playerPlayingX = xPlr; // Will be 1 or 2.
playerPlayingO = 3 - xPlr; // The other player ( 3 - 1 = 2, and 3 - 2 = 1 )
currentPlayer = playerPlayingX;
gameEndedInTie = false;
winner = -1;
gameInProgress = true;
}
private boolean winner() {
if (board[0][0] != ' '
&& (board[0][0] == board[1][1] && board[1][1] == board[2][2])) {
return true;
}
if (board[0][2] != ' '
&& (board[0][2] == board[1][1] && board[1][1] == board[2][0])) {
return true;
}
for (int row = 0; row < 3; row++) {
if (board[row][0] != ' '
&& (board[row][0] == board[row][1] && board[row][1] == board[row][2])) {
return true;
}
}
for (int col = 0; col < 3; col++) {
if (board[0][col] != ' '
&& (board[0][col] == board[1][col] && board[1][col] == board[2][col])) {
return true;
}
}
return false;
}
private boolean tie() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
}
}
For the time measurement I have the "Countdown" class, which aim is to change the players after the required time elapsed.
public class Countdown {
int timer;
public void counter(int timeFrame) {
timer = timeFrame;
Timer TimerA = new Timer();
TimerTask TaskA = new TimerTask() {
#Override
public void run() {
if (timer >= 0) {
timer--;
}
if (timer == -1) {
currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
TimerA.cancel();
}
}
};
TimerA.schedule(TaskA, 0, 1000);
}
public int getTimer(){
return timer;
}
}
Exactly at that part I'm stuck. In my opinion I need to add and start the timer somewhere in the "GameState" class, but for some reason I can't figure it out where exactly.
int timeFrame = 10;
Countdown C = new Countdown();
C.counter(timeFrame);
I thought it should be started in that "else block"
else {currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
int timeFrame = 10;
Countdown C = new Countdown();
C.counter(timeFrame);}
But it doesn't work properly => it works just for "playerPlayingO" (if he delays 10 seconds, he misses his turn). playerPlayingX is not affected...
May be I'm also missing something else...
If you're using a JavaFX you may use a task for this - Just make the task run something like this:
Thread.sleep(10000); //Wait 10 Secs
if (activePlayer == initialActivePlayer) switchPlayer(); //Better write your own "ShouldWeSwitch"-Condition
You may need to fiddle around with synchronization a little and maybe terminate the tasks when the players trigger the switch but this may work for your game.
PS: If you're not using JavaFX you can simply make your own Task by creating a class that extends Thread

need help on my tic tac toe demo invalid top level statement

public class TicTacToe
{
private char currentPlayer;
private char[][] board;
public TicTacToe()
{
board = new char [3][3];
currentPlayer = 'x';
startBoard();
}
public void startBoard()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = '-';
}
}
}
public void makeBoard()
{
System.out.println("---------------");
for (int i = 0; i < 3; i++)
{
System.out.print("| ");
for (int j = 0; j < 3; j++)
{
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("---------------");
}
}
public boolean fullBoard()
{
boolean full = true;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '-')
{
full = false;
}
}
}
return full;
}
public boolean win()
{
return (rowWin() || columnWin() || diagWin());
}
private boolean rowWin()
{
for (int i = 0; i < 3; i++)
{
if (rowColumn(board[i][0], board[i][1], board[i][2]) == true)
{
return true;
}
}
return false;
}
private boolean columnWin()
{
for (int i = 0; i < 3; i++)
{
if (rowColumn(board[0][i], board[1][i], board[2][i]) == true)
{
return true;
}
}
return false;
}
private boolean diagWin()
{
return ((rowColumn(board[0][0], board[1][1], board[2][2]) == true) ||
(rowColumn(board[0][2], board[1][1], board[2][0]) == true));
}
private boolean rowColumn(char rc1, char rc2, char rc3)
{
return ((rc1 != '-') && (rc1 == rc2) && (rc2 == rc3));
}
public void playerChange()
{
if (currentPlayer == 'x')
{
currentPlayer = 'o';
}
else
{
currentPlayer = 'x';
}
}
public boolean placeMark(int row, int column)
{
if ((row >= 0) && (row < 3))
{
if ((column >= 0) && (column < 3))
{
if (board[row][column] == '-')
{
board[row][column] = currentPlayer;
return true;
}
}
}
return false;
}
}
public class TicTacToedemo
{
public static void main(String[] args)
{
TicTacToe demo = new TicTacToe();
demo.makeBoard();
if (demo.win())
System.out.println("Winner! Hooray!");
else if (demo.fullBoard())
System.out.println("Cat Scratch, Draw.");
demo.playerChange();
}
}
I am not sure how to play the game right, every time I input numbers when I run it, I get the error code. What have I done wrong with this? The code can be compiled and runs and displays the board but when I go to put in the place I want the x or the o to go I get the error code " invalid Top level statement "
You have to use the Scanner class to make a player input using import java.util.Scanner then storing the input. After the import it going to look like this:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
And you have to manage the sc.nextInt() result, in this example the input variable.

trouble with yahtzee in java

I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.

Categories