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.
Related
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
My connect four game program works when the GRID_HEIGHT and GRID_WIDTH is the same but my assignment requires the height to be 6 and the width to be 7. It doesn't work when I set it to 6 and 7 however for some reason it works when the width is 7 and the height is 6, though I need the opposite. For this version, the system instantly crashes when an input is entered, though it works perfectly on a square grid. Thanks for any help!
import java.util.Scanner;
public class WrittenStuff
{
public static final int GRID_HEIGHT=7;
public static final int GRID_WIDTH=7;
int totalMovesPlayed;
char[][] board;
public WrittenStuff()
{
board=new char[GRID_HEIGHT][GRID_WIDTH];
totalMovesPlayed=0;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
WrittenStuff c4=new WrittenStuff();
System.out.println("WELCOME TO CONNECT FOUR!!!");
c4.printBoard();
outer:
while(true)
{
int column=0;
//PLAYER 1.
while(true)
{
System.out.print("\n\nPlayer 1 play:");
column = input.nextInt();
column = column-1;
if(c4.isPlayable(column))
{
if(c4.playMove(column, 'X'))
{
c4.printBoard();
System.out.println("\n\nPlayer 1 wins!!!");
break outer;
}
break;
}
else{
System.out.println("Column "+column+" is already full!!");
}
}
c4.printBoard();
//PLAYER 2.
while(true)
{
System.out.print("\n\nPlayer 2 play:");
column = input.nextInt();
column = column-1;
if(c4.isPlayable(column))
{
if(c4.playMove(column, 'O'))
{
c4.printBoard();
System.out.println("\n\nPlayer 2 wins!!!");
break outer;
}
break;
}
else{
System.out.println("Column "+column+" is already full!!");
}
}
c4.printBoard();
if(c4.isFull())
{
System.out.print("Game drawn. Both of you suck at this!!! ");
break;
}
}
}
public void printBoard()
{
for(int vert=0;vert<board.length;vert++)
{
for(int hori=0;hori<board[0].length;hori++)
{
if(board[vert][hori] == 0)
{
System.out.print("|" + "_" + "|");
}
else
{
System.out.print("|" + board[vert][hori] + "|");
}
}
System.out.println();
}
for(int vert=0;vert<GRID_WIDTH;vert++)
System.out.print(" "+(vert+1)+" ");
System.out.println();
}
public boolean playMove(int column, char playerNum)
{
int vert=0;
for(vert=0;vert<GRID_HEIGHT;vert++)
{
if(board[vert][column] == 'X' || board[vert][column] == 'O')
{
board[vert-1][column]=playerNum;
break;
}
}
if(vert == GRID_HEIGHT)
{
board[vert-1][column]=playerNum;
}
totalMovesPlayed++;
return isConnected(vert-1,column);
}
public boolean isPlayable(int column)
{
return board[0][column] == 0;
}
public boolean isFull()
{
return totalMovesPlayed == GRID_HEIGHT*GRID_WIDTH;
}
public boolean isConnected(int x, int y)
{
int num=board[x][y];
int count=0;
int vert=y;
//HORIZONTAL.
while(vert<GRID_WIDTH && board[x][vert] == num)
{
count++; vert++;
}
vert=y-1;
while(vert>=0 && board[x][vert] == num)
{
count++; vert--;
}
if(count == 4){
return true;}
//VERTICAL.
count=0; int hori=x;
while(hori<GRID_HEIGHT && board[hori][y] == num)
{
count++; hori++;
}
if(count == 4){
return true;}
//SECONDARY DIAGONAL.
count=0; vert=x; hori=y;
while(vert<GRID_WIDTH && hori<GRID_HEIGHT && board[vert][hori] == num)
{
count++; vert++; hori++;
}
vert=x-1; hori=y-1;
while(vert>=0 && hori>=0 && board[vert][hori] == num)
{
count++; vert--; hori--;
}
if(count == 4){
return true;}
//LEADING DIAGONAL.
count=0; vert=x; hori=y;
while(vert<GRID_WIDTH && hori>=0 && board[vert][hori] == num)
{
count++; vert++; hori--;
}
vert=x-1; hori=y+1;
while(vert>=0 && hori<GRID_HEIGHT && board[vert][hori] == num)
{
count++; vert--; hori++;
}
if(count == 4){
return true;}
return false;
}
}
Looking at all your uses of board, I find:
board[vert][hori]
board[vert][hori]
board[vert][column]
board[vert][column]
board[vert-1][column]
board[vert-1][column]
board[0][column]
board[x][y]
board[x][vert]
board[x][vert]
board[hori][y]
board[vert][hori]
board[vert][hori]
board[vert][hori]
board[vert][hori]
So, if first dimension is indexed by vert, and second dimension is indexed by hori, why is second dimension variable sometimes named column, not hori? Consistent naming is important for the human understanding of your code, including your own, to prevent coding errors.
But more importantly, what's up with the [x][y], [x][vert], and [hori][y]? Assuming y is equivalent to vert, and that x is equivalent to hori (again, consistent naming, please), aren't those reversed?
i have a class in a java program where i am using a toString function to retrieve data. the toString checks a private function in the same class which returns a int value, for displaying different types of return messages.~
The problem is that if i use a local variable in the string function every turns out good, but if i check in the if statements directlly the private function, this function doesnt return any value.
private int computerTryHorizontalPlay() {
int repeatedMyValueCount = 0;
int repeatedYourValueCount = 0;
int[] myPositions = new int[3];
int[] yourPositions = new int[3];
for (int a = 0; a < 3; a++) {
int repeatedMyValue = 0;
int repeatedYourValue = 0;
int emptyFields = 0;
int[] emptyPosition = new int[2];
for (int b = 0; b < 3; b++) {
if (jogoGalo[a][b] == 'X') {
repeatedMyValue++;
} else if (jogoGalo[a][b] == 'O') {
repeatedYourValue++;
}
if (jogoGalo[a][b] == '-') {
emptyPosition[0] = a;
emptyPosition[1] = b;
emptyFields++;
}
}
if (repeatedMyValue == 3 || repeatedYourValue == 3) {
return 3;
} else {
if (emptyFields == 1) {
if (repeatedMyValue == 2) {
repeatedMyValueCount++;
myPositions[repeatedMyValueCount - 1] = emptyPosition[0];
myPositions[repeatedMyValueCount] = emptyPosition[1];
} else if (repeatedYourValue == 2) {
repeatedYourValueCount++;
yourPositions[repeatedYourValueCount - 1] = emptyPosition[0];
yourPositions[repeatedYourValueCount] = emptyPosition[1];
}
}
}
}
if (repeatedMyValueCount > 0) {
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
This doesn´t work!
public String toString() {
if(computerTryHorizontalPlay() == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay() == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay() == 1) {
return "Computer defendeu!";
}
return null;
}
This works!
public String toString() {
int horizontalFunctionValue = computerTryHorizontalPlay();
if(horizontalFunctionValue == 3) {
return "The game has already ended!";
}
else if(horizontalFunctionValue == 2) {
return "Computer won!";
}
else if(horizontalFunctionValue == 1) {
return "Computer defendeu!";
}
return null;
}
}
toString() must be a read-only method, i.e. it is not allowed to have side-effects like changing the state of the object. Since computerTryHorizontalPlay() is a state-changing method, you are not allowed to call it from toString().
Since the only state-change happens in the last if statement, you can change the code to not execute the play when called from toString(), like this:
private int computerTryHorizontalPlay() {
return computerTryHorizontalPlay(true);
}
private int computerTryHorizontalPlay(boolean doMove) {
// lots of code here
if (repeatedMyValueCount > 0) {
if (doMove)
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
if (doMove)
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
public String toString() {
if(computerTryHorizontalPlay(false) == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay(false) == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay(false) == 1) {
return "Computer defeated!";
}
return null;
}
I am doing an assignment for school. It is a towers of hanoi assignment. (I didn't add the larger-disk-over-smaller-disk code yet). When I set tower3 as 4, 3, 2, 1, it says I won, but when I do it while playing the game, nothing happens. Please help! This is due Monday 8:30pm EST.
import java.util.Scanner;
/**
* Simulates a tower that can hold disks.
* #author S. Camilleri
* #author <Hasan Zafar>
*/
public class Challenge {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// This array holds the disks. A 0 represents no disk.
int[] tower = {4,3,2,1};
int[] tower2 = {0,0,0,0};
int[] tower3 = {0,0,0,0};
// This index represents the first available empty spot for a disk.
int index = 0;
int towerCounter = 0;
int length = tower.length;
int length2 = tower2.length;
int length3 = tower3.length;
int diskChoice = 1;
int i;
int held = 0;
int placeChoice;
boolean playing = true;
while (playing)
{
//Check if Won
if (tower3[0] == 4 && tower3[1] == 3 && tower3[2] == 2 && tower[3] == 1) {
System.out.println("Congratulations! You win!");
playing = false;
break;
}
/********************
* Display the towers
********************/
System.out.println();
//Tower1
System.out.print("{ ");
for (int x=0; x<length; x++)
{
System.out.print(tower[x]);
}
System.out.println();
//Tower2
System.out.print("{ ");
towerCounter = 0;
for (int x=0; x<length2; x++)
{
System.out.print(tower2[x]);
}
System.out.println();
//Tower3
System.out.print("{ ");
towerCounter = 0;
for (int x=0; x<length3; x++)
{
System.out.print(tower3[x]);
}
/********************
* Select the highest disk from the tower
********************/
System.out.println();
System.out.println("Pick a tower (The disk highest on that tower will be chosen)");
diskChoice = input.nextInt();
// If user uses the first tower
if (diskChoice == 1) {
i = 3;
while (tower[i] == 0) {
i--;
}
held = tower[i];
tower[i] = 0;
} else if (diskChoice == 2) { // If user uses the second tower
i = 3;
while (tower2[i] == 0) {
i--;
}
held = tower2[i];
tower2[i] = 0;
} else if (diskChoice == 3) { // If user uses the third tower
i = 3;
while (tower3[i] == 0) {
i--;
}
held = tower3[i];
tower3[i] = 0;
}
/********************
* Place the disk
********************/
System.out.println("Where would you like to place" + " " + held + "?");
placeChoice = input.nextInt();
if (placeChoice == 1) {
i = 3;
if (tower[3] == 0){
while (tower[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower[i] == 0) {
tower[i] = held;
} else if (tower[i] != 0) {
tower[i+1] = held;
}
} else if (placeChoice == 2) {
i = 3;
if (tower2[3] == 0){
while (tower2[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower2[i] == 0) {
tower2[i] = held;
} else if (tower2[i] != 0) {
tower2[i+1] = held;
}
} else if (placeChoice == 3) {
i = 3;
if (tower3[3] == 0){
while (tower3[i] == 0) {
i--;
if (i == 0) {
break;
}
}
}
if (tower3[i] == 0) {
tower3[i] = held;
} else if (tower3[i] != 0) {
tower3[i+1] = held;
}
}
}
}
}
If I set tower3 as 4321 manually, it says I won.
If I set tower3 as 4321 in-game, it just keeps playing.
I figured it out. I forgot to write the 3 at the of win statement.
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