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
Related
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
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
}
...
}
}
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.
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.
I am a beginner at programming and I have been teaching myself as much as I can. I need help in a simpler way of checking for a victory instead of hard coding every possible combination.
I have no idea what to do.
here is my current code:
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class connectfour extends JFrame implements ActionListener
{
JLabel board[][] = new JLabel[8][7];
//JLabel board[] = new JLabel[64];
JButton action[] = new JButton[8];
JButton start;
JButton clear;
JFrame Frame = new JFrame();
ImageIcon red = new ImageIcon("red piece.jpeg");
ImageIcon black = new ImageIcon("blackpiece.jpeg");
boolean players = true;
//Integer[] numclick = new Integer[8];
int x;
int numclick1 = 7;
int numclick2 = 7;
int numclick3 = 7;
int numclick4 = 7;
int numclick5 = 7;
int numclick6 = 7;
int numclick7 = 7;
int numclick0 = 7;
public connectfour()
{
Frame.setSize(100,120);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setLayout(null);
Frame.setVisible(true);
start = new JButton("Start");
start.setBounds(0,0,100,100);
start.setVisible(true);
start.addActionListener(this);
Frame.add(start);
}
public void game()
{
for(int x = 0; x < 8 ; x++)
{
action[x] = new JButton();
action[x].setSize(100,40);
action[x].setLocation((x*100) + 50, 0);
action[x].addActionListener(this);
action[x].setVisible(true);
Frame.add(action[x]);
}
/**
board[1][1] = new JLabel();
board[1][1].setBounds(50,40,100,100);
board[1][1].setVisible(true);
board[1][1].setOpaque(true);
board[1][1].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[1][1]);
**/
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new JLabel();
board[i][j].setSize(100,100);
board[i][j].setLocation((i*100)+50,(j*100)+40);
board[i][j].setOpaque(true);
board[i][j].setVisible(true);
board[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[i][j]);
}
}
clear = new JButton("Clear");
clear.setBounds(850,100,100,50);
clear.addActionListener(this);
clear.setVisible(true);
Frame.add(clear);
}
public void boardsize()
{
Frame.setSize(950,800);
}
public static void main(String args[])
{
new connectfour();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
boardsize();
start.setVisible(false);
game();
}
for(x = 0;x < 8 ;x ++)
{
if(e.getSource() == action[x])
{
//numclick[x]++;
if(x == 0)
{
numclick0--;
if(players == true)
{
board[x][numclick0].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick0].setIcon(black);
players = true;
break;
}
}
if(x == 1)
{
numclick1--;
if(players == true)
{
board[x][numclick1].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick1].setIcon(black);
players = true;
break;
}
}
if(x == 2)
{
numclick2--;
if(players == true)
{
board[x][numclick2].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick2].setIcon(black);
players = true;
break;
}
}
if(x == 3)
{
numclick3--;
if(players == true)
{
board[x][numclick3].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick3].setIcon(black);
players = true;
break;
}
}
if(x == 4)
{
numclick4--;
if(players == true)
{
board[x][numclick4].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick4].setIcon(black);
players = true;
break;
}
}
if(x == 5)
{
numclick5--;
if(players == true)
{
board[x][numclick5].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick5].setIcon(black);
players = true;
break;
}
}
if(x == 6)
{
numclick6--;
if(players == true)
{
board[x][numclick6].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick6].setIcon(black);
players = true;
break;
}
}
if(x == 7)
{
numclick7--;
if(players == true)
{
board[x][numclick7].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick7].setIcon(black);
players = true;
break;
}
}
System.out.println(x);
System.out.println();
}
}
if(e.getSource() == clear)
{
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 7; y++)
{
board[x][y].setIcon(null);
numclick1 = 7;
numclick2 = 7;
numclick3 = 7;
numclick4 = 7;
numclick5 = 7;
numclick6 = 7;
numclick7 = 7;
numclick0 = 7;
players = true;
for(int j = 0; j < 8 ; j++)
{
action[j].setEnabled(true);
}
}
}
}
if(numclick0 == 0)
{
action[0].setEnabled(false);
}
if(numclick1 == 0)
{
action[1].setEnabled(false);
}
if(numclick2 == 0)
{
action[2].setEnabled(false);
}
if(numclick3 == 0)
{
action[3].setEnabled(false);
}
if(numclick4 == 0)
{
action[4].setEnabled(false);
}
if(numclick5 == 0)
{
action[5].setEnabled(false);
}
if(numclick6 == 0)
{
action[6].setEnabled(false);
}
if(numclick7 == 0)
{
action[7].setEnabled(false);
}
}
public void winner()
{
}
}
I would use a recursive method that checks the horizontal, vertical, and both diagonals.
As i was reading your code I realized you don't keep track(may have missed it) of where players are.. I recommend and array for this called grid[][] Mapping an array to your JLabels will go a long way.
Ill give an example of negative vertical check..
public Boolean checkVertical(Boolean player, int x, int y){
if(solveHelper(player, x, y, -1, 0) => 4) return true;
return false;
}
public int solveHelper(Boolean player, int x, int y, int addX, int addY){
if(x == 0 || x == size || y == 0 || y == size || grid[x][y].player != player)
return 0;
return solverHelper(player, x+addX, y+addY, addX, addY) + 1);
}
Now how can you create and use these methods for yourself?
you need to create a new methods for each of the horizontal, vertical, and both diagonals to check for all of them you call solveHelper with different properties in addX and addY that correspond with the direction you want to go. For instance, if you want to check the horizontal you need do make addY == 1 and addY == -1 with both values for addX == 0 by doing a solveHelper + solverHelper with these two values changed.
Other notes...
Some things you need to need to keep in mind is that how connect four actually runs. When you click on a row a piece falls down to the smallest unoccupied element in that particular column. Just something you should keep in mind when writing your game logic.
Cheers.