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.
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?
So in a few words i made a class extending the RandomGenerator to randomly giving back PRIME, POWER OF 2(2,4,8,16,32,64,128 etc) , FIBONACCI AND SQUARE NUMBERS (1,4,9,16,25,36 etc). Then i made a simple program to call my class and giving back random numbers while the user defines the space (1,n). Both programs compile just fine. My problem is that when i run the program it always returns 0 for each value. I'm new to java. Can anyone help me?
import acm.util.*;
public class RandomGeneratorImproved2 extends RandomGenerator
{
private int i,j,a,c,d,e,temp,n,Pnumber,Fnumber,number2,numbersq;
private long b;
boolean flag,flag2,flag3,flag4,flag5;
private double temp1;
public RandomGeneratorImproved2 (int n)
{
this.n = n;
}
public void nextPrime(int n) // PRIME NUMBERS
{
Pnumber = rgen.nextInt(1, n);
i=2;
flag2 = false;
if ( Pnumber == 1 ) // Check for value 1 cause it cannot check it inside the loop
{
flag2=true;
}
while ( (i<n) && (flag2 == false) )
{
flag = true;
j=2;
do
{
a = i%j;
if ( (a == 0) && (i != j) )
{
flag = false;
}
if (i!=j-1)
{
j = j+1;
}
} while ( j<i );
if ((flag == true) && (Pnumber==i)) //
{
flag2 = true;
}
if ((i==99) && (flag2==false)) // restart if the number is not prime
{
i = 1;
Pnumber = rgen.nextInt(1, n);
}
i = i + 1;
}
}
public int getPrime() //POWER OF 2 NUMBERS
{
return Pnumber;
}
public void nextPowerof2(int n)
{
number2 = rgen.nextInt(1, n);
i=1;
b=2;
flag3 = false;
while ( i<n ) // n <= 31
{
if (number2 == b)
{
flag3 = true;
}
b = 2*b;
if ((i == n-1) && (flag3==false))
{
i=1;
number2 = rgen.nextInt(1,n);
b=2;
}
i=i+1;
}
}
public int getPowerof2()
{
return number2;
}
public void nextFibonacciNumber(int n) // FIBONACCI NUMBERS
{
Fnumber = rgen.nextInt(1, n);
c=0;
d=1;
flag4 = false;
i=1;
while ( i<n && flag4==false )
{
temp = d;
d = d + c;
c = temp;
i=i+1;
if (Fnumber == d)
{
flag4 = true;
}
if ((flag4 == false) && (i==n))
{
i=1;
c=0;
d=1;
Fnumber = rgen.nextInt(1, n);
}
}
}
public int getFibonacciNumber()
{
return Fnumber;
}
public void setSquareNumber(int n) // SQUARE NUMBERS
{
numbersq = rgen.nextInt(1, n);
flag5 = false;
i=1;
temp1 = Math.sqrt(n);
while ( i<temp1 && flag5 == false )
{
e = i*i;
i = i + 1;
if ( numbersq == e )
{
flag5 = true;
}
if ( i == 20 && flag5 == false )
{
i=1;
numbersq = rgen.nextInt(1, n);
}
}
}
public int getSquareNumber()
{
return numbersq;
}
public String toString()
{
return "Your Prime number is : " + Pnumber + "\nYour Power of 2 number is : " + number2 + "\nYour Fibonacci number is : " + Fnumber + "\nYour square number is : " + numbersq;
}
private RandomGenerator rgen = RandomGenerator.getInstance();
}
import acm.program.*;
public class caller2 extends Program
{
public void run()
{
int n = readInt("Please give me an integer to define the space that i'll look for numbers : ");
RandomGeneratorImproved2 r1 = new RandomGeneratorImproved2(n);
println(r1);
}
}
As stated you've only defined those method. You never call any of the methods that are setting those values so all are still in their initialized state. Try adding the following to the constructor after setting n;
nextPrime(n);
nextFibonaccitNumber(n);
nextPowerof2(n);
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.