Connect Four victory check not working Java [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've coded an entire program to play Connect Four, but the algorithm for checking who has won (after each turn) isn't working and I don't know why. I keep getting a weird message when I compile it (exception ArrayIndexOutOfBoundsException). Any help is appreciated.
Here is the code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class connectFourDemo extends Applet
implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
int[][] myGrid = new int[7][6];
// If piece is 0, white. If 1, red. If 2, black.
int xCoord, yCoord; // X and Y co-ordinates for mouse navigation.
int width, height;
int playerTurn = 1; // Player's turn. Default is 1 since red goes first.
int mx, my; // The mouse coordinates.
boolean isButtonPressed = false;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground(Color.yellow);
mx = width / 2;
my = height / 2;
addMouseListener(this);
addMouseMotionListener(this);
}
private int getXValue(int xValue) {
if (xValue < width / 7) return 0;
else if (xValue < width / 7 * 2) return 1;
else if (xValue < width / 7 * 3) return 2;
else if (xValue < width / 7 * 4) return 3;
else if (xValue < width / 7 * 5) return 4;
else if (xValue < width / 7 * 6) return 5;
else return 6;
}
private int getYValue(int yValue) {
if (yValue < width / 6) return 0;
else if (yValue < width / 6 * 2) return 1;
else if (yValue < width / 6 * 3) return 2;
else if (yValue < width / 6 * 4) return 3;
else if (yValue < width / 6 * 5) return 4;
else return 5;
}
public void verticalCheck(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 5; i >= 0; i--) {
if (myGrid[xCoord][i] == 1) {
System.out.println("Counter one in vertical check is " + counter + ".");
if (myGrid[xCoord][i - 1] == 1 && (i - 1 >= 0)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four vertically!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 5; i >= 0; i--) {
if (myGrid[xCoord][i] == 2) {
System.out.println("Counter two in vertical check is " + counter + ".");
if (myGrid[xCoord][i - 1] == 2 && (i - 1 >= 0)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four vertically!");
}
}
}
public void horizontalCheck(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
if (myGrid[i][y] == 1) {
System.out.println("Counter one in horizontal check is " + counter + ".");
if (myGrid[i + 1][y] == 1 && (i + 1 <= 6)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four horizontally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
if (myGrid[i][y] == 2) {
System.out.println("Counter two in horizontal check is " + counter + ".");
if (myGrid[i + 1][y] == 2 && (i + 1 <= 6)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four horizontally!");
}
}
}
public void diagonalCheckRight(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
for (int j = 5; j >= 0; j--) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four diagonally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 2) {
System.out.println("Counter two in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four diagonally!");
}
}
}
public void diagonalCheckLeft(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check left is " + counter + ".");
if (myGrid[i - 1][j - 1] == 1 && (i + 1 <= 6) && (j - 1 >= 0)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four diagonally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 2) {
System.out.println("Counter one in diagonal check left is " + counter + ".");
if (myGrid[i - 1][j - 1] == 2 && (i <= 6) && (j >= 0)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four diagonally!");
}
}
}
public void mouseEntered( MouseEvent e ) {
// Called when the pointer enters the applet's rectangular area.
}
public void mouseExited( MouseEvent e ) {
// Called when the pointer leaves the applet's rectangular area.
}
public void mouseClicked( MouseEvent e ) {
// Called after a press and release of a mouse button with no motion in between.
mx = e.getX();
my = e.getY();
xCoord = getXValue(mx);
yCoord = getYValue(my);
if (myGrid[xCoord][yCoord] == 0 && playerTurn == 1) { // Drop from top, fall to bottom and vice versa.
for (int y = 5; y >= yCoord; y--) {
if (myGrid[xCoord][y] == 0) {
myGrid[xCoord][y] = 1;
y = yCoord - 1;
}
}
verticalCheck(xCoord, yCoord);
horizontalCheck(xCoord, yCoord);
diagonalCheckRight(xCoord, yCoord);
diagonalCheckLeft(xCoord, yCoord);
playerTurn = 2;
}
else if (myGrid[xCoord][yCoord] == 0 && playerTurn == 2) {
for (int y = 5; y >= yCoord; y--) {
if (myGrid[xCoord][y] == 0) {
myGrid[xCoord][y] = 2;
y = yCoord - 1;
}
}
verticalCheck(xCoord, yCoord);
horizontalCheck(xCoord, yCoord);
diagonalCheckRight(xCoord, yCoord);
diagonalCheckLeft(xCoord, yCoord);
playerTurn = 1;
}
}
public void mousePressed(MouseEvent e) { // Called after a button is pressed down.
repaint();
// "Consume" the event so it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
public void mouseReleased(MouseEvent e) { // Called after a button is released.
repaint();
e.consume();
}
public void mouseMoved(MouseEvent e) { // Called during motion when no buttons are down.
mx = e.getX();
my = e.getY();
mx = mx / 50; // Divides applet width by the width of each oval (50).
my = my / 50; // Divides applet height by the height of each oval (50).
showStatus("Mouse in column " + (mx + 1) + ", row " + (my + 1) + ".");
}
public void mouseDragged(MouseEvent e) { // Called during motion with buttons down.
}
public void paint(Graphics g) {
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
if (myGrid[x][y] == 0) {
g.setColor(Color.white);
}
if (myGrid[x][y] == 1) {
g.setColor(Color.red);
}
if (myGrid[x][y] == 2) {
g.setColor(Color.black);
}
g.fillOval((width / 7) * x + 2, (height / 6) * y + 1, (width / 7) - 4, (height / 6) - 4);
}
}
}
}

Ran the code, your problem is in "diagonalCheckRight", namely this section:
for (int i = 0; i <= 6; i++) {
for (int j = 5; j >= 0; j--) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
Your j index starts at 5, in the if you do myGrid[i+1][j+1] so that means on the first iteration you're accessing myGrid[1][6], however you defined myGrid to be of size [7][6] and so you're out of bounds because the valid indices are: [0..6][0..5].
Also next time look at the error message, my console was showing:
java.lang.ArrayIndexOutOfBoundsException: 6
at Main.diagonalCheckRight(Main.java:134)
I renamed the class to Main, and that 134 is exactly the line number where I found the error.

Related

Heuristics for 3D tic-tac-toe

Currently I'm trying to implement heuristics for a 3D tic-tac-toe but it seems like my counter is way of it,f but I'm unsure where I've done wrong, I'm not gonna post all of the code since it's a lot, but here is a part:
public void countDiagonal(GameState gameState) {
/*
* yz-plane (negativ)
*/
int z;
for (int x = 0; x < GameState.BOARD_SIZE; x++) {
for (int y = 0; y < GameState.BOARD_SIZE; y++) {
z = y;
if (gameState.at(x, y, z) == myPlayer) {
myCounter++;
opponentCounter = 0;
}
if (gameState.at(x, y, z) == opponentPlayer) {
opponentCounter++;
myCounter = 0;
}
if (gameState.at(x, y, z) == Constants.CELL_EMPTY) {
emptyCells++;
}
}
evaluateBoard();
myCounter = 0;
opponentCounter = 0;
emptyCells = 0;
}
The evaluation is done here:
public void evaluateBoard() {
if (myCounter == 1 && emptyCells == 3) {
myScore = myScore + 5;
}
if (myCounter == 2 && emptyCells == 2) {
myScore = myScore + 10;
}
if (myCounter == 3 && emptyCells == 1) {
myScore = myScore + 20;
}
if (myCounter == 4) {
myScore = myScore + 1000;
}
if (opponentCounter == 1 && emptyCells == 3) {
opponentScore = opponentScore + 5;
}
if (opponentCounter == 2 && emptyCells == 2) {
opponentScore = opponentScore + 10;
}
if (opponentCounter == 3 && emptyCells == 1) {
opponentScore = opponentScore + 20;
}
if (opponentCounter == 4) {
opponentScore = opponentScore + 1000;
}
}
When I try to run it, I use alpha-beta prune, but it seems like the calculation are done horrbly wrong, when I use the value, I take myScore - opponentScore and I use an alpha-beta tree with depth 1, but even after only playing one move, I'm down -15 in points, as I'm a noob in java, im therefore asking for help, is there an obvious mistake in my way of trying to evaluate the board?

im having trouble in while loop

I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.

Java: Using MouseListener to change the color of adjacent JButtons

I have a 15 x 15 2D array of JButton.
When I hold one of those buttons (i.e. Button[i][j]),
I would like to change the color of adjacent buttons (i.e. Button[i-1][j], Button[i+1][j], Button[i][j-1], Button[i][j+1]).
How do I do this?
Below is the part of my implementation of my 2D array. The button doesn't do anything for now.
fb = new JButton[15][15];
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
fb[i][j] = new JButton();
fb[i][j].setBackground(Color.WHITE);
fb[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
fb[i][j].setPreferredSize(new Dimension(40, 40));
//fb[i][j].setEnabled(false);
grid.add(fb[i][j]);
}
}
try this block:
if (i - 1 >= 0) {
if (fb[i - 1][j] != null) {
fb[i - 1][j].setBackground(Color.RED);
}
} else if (i + 1 < 15) {
if (fb[i + 1][j] != null) {
fb[i + 1][j].setBackground(Color.RED);
}
} else if (j - 1 >= 0) {
if (fb[i][j - 1] != null) {
fb[i][j - 1].setBackground(Color.RED);
}
} else if (j + 1 < 15) {
if (fb[i][j + 1] != null) {
fb[i][j + 1].setBackground(Color.RED);
}
}
and listener:
fb[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
int x, y;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if(fb[i][j].equals(b)){
x = i;
y = j;
break;
}
}
}
if (x - 1 >= 0) {
if (fb[x - 1][y] != null) {
fb[x - 1][y].setBackground(Color.RED);
}
} else if (x + 1 < 15) {
if (fb[x + 1][y] != null) {
fb[x + 1][y].setBackground(Color.RED);
}
} else if (y - 1 >= 0) {
if (fb[x][y - 1] != null) {
fb[x][y - 1].setBackground(Color.RED);
}
} else if (y + 1 < 15) {
if (fb[x][y + 1] != null) {
fb[x][y + 1].setBackground(Color.RED);
}
}
}
});

Flagging Buttons for Minesweeper GUI Game

I have worked for hours on this code and finally gotten ver close to completion. I will be adding a Mine Counter and a timer once I figure out how to add the ability to flag mines with right clicking. I learned that JButtons do not recognize right clicks, so I must use a MouseEvent. From there, I'm lost. Can someone give me a nudge in the right direction?
This is what I currently have:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
public class MineSweeper implements ActionListener {
JFrame frame = new JFrame("Mine Sweeper");
JButton reset = new JButton("Reset");
JButton[][] buttons = new JButton[20][20];//button array
JButton[] flags = new JButton[20];
int[][] counts = new int[20][20];
Container grid = new Container(); //grid for buttons
int MineNum = 50;//number of mines
final int MINE = 10;//int value to identify a mine
public MineSweeper() {
frame.setSize(500, 500);
frame.setLayout(new BorderLayout());
frame.add(reset, BorderLayout.NORTH);
reset.addActionListener(this);
//Grid of Buttons
grid.setLayout(new GridLayout(20,20));
for (int a = 0; a<buttons.length; a++) {
for (int b = 0; b < buttons[0].length; b++) {
buttons[a][b] = new JButton("▒");
buttons[a][b].addActionListener(this);
buttons[a][b].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
mineFlagger(true);
}
}
});
grid.add(buttons[a][b]);
}
}
frame.add(grid, BorderLayout.CENTER);
makeRandomMines();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void mineFlagger (boolean flag){
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[0].length; j++) {
if(flag == true) {
buttons[i][j].setText("F");
}
}
}
}
public static void main(String[] args) {
new MineSweeper();
}
public void makeRandomMines() {
//initializes list of random pairs
ArrayList<Integer> list = new ArrayList<Integer>();
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
list.add(x * 100 + y);//changed y to x
}
}
//resets the counts in case reset button is pressed & picks random mines
counts = new int[20][20];
for (int i = 0; i < MineNum; i++) {
int choice = (int) (Math.random() * list.size());
counts[list.get(choice) / 100][list.get(choice) % 100] = MINE;
list.remove(choice);
}
//neighbor counts(how many mines are touching this square.)
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
int neighborCount = 0;
if (counts[x][y] != MINE) {
if(x > 0 && y > 0 && counts[x - 1][y - 1] == MINE) { //a mine is up & left
neighborCount++;
}
if(y > 0 && counts[x][y - 1] == MINE) { //a mine is up
neighborCount++;
}
if(x < counts.length - 1 && y > 0 && counts[x + 1][y - 1] == MINE) { // a mine is left
neighborCount++;
}
if(x > 0 && counts[x - 1][y] == MINE) { //left
neighborCount++;
}
if(x < counts.length - 1 && counts[x + 1][y] == MINE) { //mine is right
neighborCount++;
}
if(x > 0 && y < counts[0].length - 1 && counts[x - 1][y + 1] == MINE) { //mine is down
neighborCount++;
}
if(y < counts[0].length - 1 && counts[x][y + 1]== MINE) {//mine is up right
neighborCount++;
}
if(x < counts[0].length - 1 && y < counts[0].length - 1 && counts[x + 1][y + 1]== MINE) {//mine is down left
neighborCount++;
}
counts[x][y] = neighborCount;
}
}
}
}
public void lostGame() {
for (int x = 0; x < buttons.length; x++) {
for (int y = 0; y < buttons[0].length; y++) {
if (buttons[x][y].isEnabled()) {
if (counts[x][y] != MINE) {
buttons[x][y].setText(counts[x][y] + "");
buttons[x][y].setEnabled(false);
}
else {
buttons[x][y].setText("✪");
buttons[x][y].setEnabled(false);
}
}
}
}
JOptionPane.showMessageDialog(null, "You Lose!\n" + "You clicked on a mine!", "BOOM!", JOptionPane.INFORMATION_MESSAGE);
}
public void checkWin() {
boolean winner = true;
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
if (counts[x][y] != MINE && buttons[x][y].isEnabled()) {
winner = false;
}
}
}
if (winner == true) {
JOptionPane.showMessageDialog(frame, "You win!");
}
}
public void zeroCleaner(ArrayList<Integer> toClear) {
if (toClear.size() == 0) {
return;
}
else {
int x = toClear.get(0) / 100;
int y = toClear.get(0) % 100;
toClear.remove(0);
if(x > 0 && y > 0 && buttons[x-1][y-1].isEnabled()) { //up and left
buttons[x - 1][y - 1].setText(counts[x-1][y-1] + "");
buttons[x - 1][y - 1].setEnabled(false);
if (counts[x - 1][y - 1] == 0) {
toClear.add((x-1) * 100 + (y-1));
}
}
if (y > 0 && buttons[x][y-1].isEnabled()) { // up
buttons[x][y - 1].setText(counts[x][y-1] + "");
buttons[x][y - 1].setEnabled(false);
if (counts[x][y - 1] == 0) {
toClear.add(x * 100+(y - 1));
}
}
if (x < counts.length - 1 && y > 0 && buttons[x+1][y-1].isEnabled()) { //up right
buttons[x + 1][y - 1].setText(counts[x+1][y-1] + "");
buttons[x + 1][y - 1].setEnabled(false);
if (counts[x + 1][y - 1] == 0) {
toClear.add((x + 1)*100+(y - 1));
}
}
if(x > 0 && y > 0 && buttons[x-1][y].isEnabled()) { //left
buttons[x - 1][y].setText(counts[x-1][y] + "");
buttons[x - 1][y].setEnabled(false);
if (counts[x-1][y] == 0) {
toClear.add((x-1)*100+y);
}
}
if (x < counts.length - 1 && buttons[x+1][y].isEnabled()) { //right
buttons[x + 1][y].setText(counts[x+1][y] + "");
buttons[x + 1][y].setEnabled(false);
if (counts[x + 1][y] == 0) {
toClear.add((x + 1)*100+y);
}
}
if(x > 0 && y < counts[0].length - 1 && buttons[x-1][y+1].isEnabled()) { //down and left
buttons[x - 1][y + 1].setText(counts[x-1][y+1] + "");
buttons[x - 1][y + 1].setEnabled(false);
if (counts[x-1][y+1] == 0) {
toClear.add((x-1)*100+(y+1));
}
}
if (y < counts[0].length - 1 && buttons[x][y+1].isEnabled()) { // down
buttons[x][y + 1].setText(counts[x][y+1] + "");
buttons[x][y + 1].setEnabled(false);
if (counts[x][y + 1] == 0) {
toClear.add(x * 100+(y + 1));
}
}
if (x < counts.length - 1 && y < counts[0].length - 1 && buttons[x+1][y+1].isEnabled()) { //down right
buttons[x + 1][y + 1].setText(counts[x+1][y+1] + "");
buttons[x + 1][y + 1].setEnabled(false);
if (counts[x + 1][y + 1] == 0) {
toClear.add((x + 1)*100+(y + 1));
}
}
zeroCleaner(toClear);
}
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset)) {
//Resets the playing field
for (int x = 0; x < buttons.length; x++) {
for (int y = 0; y < buttons[0].length; y++) {
buttons[x][y].setEnabled(true);
buttons[x][y].setText("▒");
}
}
makeRandomMines();
}
else {
for (int x = 0; x < buttons.length ; x++) {
for (int y = 0; y < buttons[0].length; y++) {
if(event.getSource().equals(buttons[x][y])) {
if (counts[x][y]== MINE) {
lostGame();
}
else if(counts[x][y] == 0) {
buttons[x][y].setText(counts[x][y]+ "");
buttons[x][y].setEnabled(false);
ArrayList<Integer> toClear = new ArrayList<>();
toClear.add(x*100+y);
zeroCleaner(toClear);
checkWin();
}
else {
buttons[x][y].setText(counts[x][y]+ "");
buttons[x][y].setEnabled(false);
checkWin();
}
}
}
}
}
}
}
This should solve your problem:
for (int a = 0; a<buttons.length; a++) {
for (int b = 0; b < buttons[0].length; b++) {
buttons[a][b] = new JButton("▒");
buttons[a][b].addActionListener(this);
final int finalB = b;
final int finalA = a;
buttons[a][b].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
mineFlagger(true, finalA, finalB);
}
}
});
grid.add(buttons[a][b]);
}
}
public void mineFlagger (boolean flag, int x, int y){
buttons[x][y].setText("F");
}
Edit: for toggling the flag (lazy implementation)
if (SwingUtilities.isRightMouseButton(e)) {
mineFlagger(finalA, finalB);
}
public void mineFlagger(int x, int y) {
if(buttons[x][y].getText().equals("F")) {
buttons[x][y].setText("▒");
} else if (buttons[x][y].getText().equals("▒")){
buttons[x][y].setText("F");
}
}
If you import 'javax.swing.SwingUtilities' you could use utilities methods:
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
Then when a right mouse button is pressed, get the location of the mouse, find the button at that location, and then use that event to change the picture on that particular button to a picture of a flag.
You could use:
MouseInfo.getPointerInfo().getLocation()
To obtain the location of the mouse relative to the screen.

John Conway's Game of Life

I have been working on a versions of Conway's Game of Life for school and I have run into a problem: cells are becoming dead or alive in the wrong places.
How can I fix that?
if (alive == 3 && aryBOARD[x][y] == 0) { //rule 4
aryCHANGE[x][y] = 1;
}
if (alive > 3 && aryBOARD[x][y] == 1) { //rule 3
aryCHANGE[x][y] = 0;
}
if (alive >= 2 && alive <= 3 && aryBOARD[x][y] == 1) { //rule 2
aryCHANGE[x][y] = 1;
}
if (alive < 2 && aryBOARD[x][y] == 1) { //rule 1
aryCHANGE[x][y] = 0;
}
if (dead > 5) { //rule check
aryCHANGE[x][y] = 0;
}
That is where I assume the problem is but if having the whole code would help:
package gameoflife2;
public class Game {
public static void main(String[] args) {
int[][] aryBOARD = new int[5][5];
int x = 0;
int y = 0;
int dead = 0;
int alive = 0;
int i, j;
// Board numbers
// 00011
// 00001
// 01000
// 01100
// 00000
aryBOARD[0][0] = 0;
aryBOARD[0][1] = 0;
aryBOARD[0][2] = 0;
aryBOARD[0][3] = 1;
aryBOARD[0][4] = 1;
aryBOARD[1][0] = 0;
aryBOARD[1][1] = 0;
aryBOARD[1][2] = 0;
aryBOARD[1][3] = 0;
aryBOARD[1][4] = 1;
aryBOARD[2][0] = 0;
aryBOARD[2][1] = 1;
aryBOARD[2][2] = 0;
aryBOARD[2][3] = 0;
aryBOARD[2][4] = 0;
aryBOARD[3][0] = 0;
aryBOARD[3][1] = 1;
aryBOARD[3][2] = 1;
aryBOARD[3][3] = 0;
aryBOARD[3][4] = 0;
aryBOARD[4][0] = 0;
aryBOARD[4][1] = 0;
aryBOARD[4][2] = 0;
aryBOARD[4][3] = 0;
aryBOARD[4][4] = 0;
// end of array
int[][] aryCHANGE = aryBOARD.clone(); // array change is equal to array
// board
// printing array
int rows = 5;
int colums = 5;
for (i = 0; i < rows; i++) {
for (j = 0; j < colums; j++) {
System.out.print(aryBOARD[i][j] + " ");
}
System.out.println("");
}
System.out.println("---------------------------");
// done printing array
// check for dead or alive cells
for (x = 0; x <= 4; x++) {
for (y = 0; y <= 4; y++) {
alive = 0;
dead = 0;
if ((x + 1 < 4) && (x + 1 > 0)) { // right
if (aryBOARD[x + 1][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y - 1 < 4) && (y - 1 > 0) && (x + 1 < 4) && (x + 1 > 0))) { // bottom
// right
// corner
if (aryBOARD[x + 1][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
if (((y + 1 < 4) && (y + 1 > 0) && (x + 1 < 4) && (x + 1 > 0))) { // top
// right
// corner
if (aryBOARD[x + 1][y + 1] == 0) {
dead++;
} else {
alive++;
}
}
if ((y + 1 < 4) && (y + 1 > 0)) {// top middle
if (aryBOARD[x][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y + 1 < 4) && (y + 1 > 0) && (x - 1 < 4) && (x - 1 > 0))) {// top
// left
// corner
if (aryBOARD[x - 1][y + 1] == 0) {
dead++;
} else {
alive++;
}
}
if ((x - 1 < 4) && (x - 1 > 0)) {// left
if (aryBOARD[x - 1][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y - 1 < 4) && (y - 1 > 0) && (x - 1 < 4) && (x - 1 > 0))) {// bottom
// left
// corner
if (aryBOARD[x - 1][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
// x++
if ((y - 1 < 4) && (y - 1 > 0)) {// bottom middle
if (aryBOARD[x][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
// RULES
// 1 Any live cell with fewer than two live neighbors dies, as if caused
// by under-population.
// 2 Any live cell with two or three live neighbors lives on to the next
// generation.
// 3 Any live cell with more than three live neighbors dies, as if by
// overcrowding.
// 4 Any dead cell with exactly three live neighbors becomes a live
// cell, as if by reproduction.
// test alive and dead
if (alive == 3 && aryBOARD[x][y] == 0) {// rule 4
aryCHANGE[x][y] = 1;
}
if (alive > 3 && aryBOARD[x][y] == 1) {// rule 3
aryCHANGE[x][y] = 0;
}
if (alive >= 2 && alive <= 3 && aryBOARD[x][y] == 1) {// rule 2
aryCHANGE[x][y] = 1;
}
if (alive < 2 && aryBOARD[x][y] == 1) {// rule 1
aryCHANGE[x][y] = 0;
}
if (dead > 5) {// rule check
aryCHANGE[x][y] = 0;
}
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < colums; j++) {
System.out.print(aryCHANGE[i][j] + " ");
}
System.out.println("");
}
System.out.println("---------------------------");
} // end main
} // end class
You need to think a lot more about structuring your code and breaking things up into smaller chunks. That will help you a lot, especially when you move onto larger projects in the future.
For example write a simple method to count the number of living cells around a given cell.
Now your main loop through just becomes:
for (int x=0;x<width;x++) {
for (int y=0;y<height;y++) {
switch(countLivingAround(x,y)) {
case 0: // Less than 2 always dies
case 1:
grid(x,y) = 0;
break;
case 2: // Do nothing, keep current state
break;
case 3: // Breed
grid(x,y) = 1;
break;
case 4: // Dies from overcrowding
grid(x,y) = 0;
break;
}
}
}
Your count function can be simple, it just adds up the values at [x-1,y],[x,y+1], etc, remember to check for the edges of the board and handle that case correctly though.
In addition to breaking the logic up into different methods you need to either use a debugger to step thru the code or use printlns to display the x and y values your evaluating (See the sample below) You'll see that some of your calculations on the adjoining cells x and y coordinates need work.
for (x = 0; x <= 4; x++) {
for (y = 0; y <= 4; y++) {
alive = 0;
dead = 0;
System.out.println("evaluating cell x=" + x + ", y = " + y);
if ((x + 1 < 4) && (x + 1 > 0)) {// right
if (aryBOARD[x + 1][y] == 0) {
dead++;
}
else {
alive++;
}
System.out.println(" check 1 x=" + (x + 1) + ", y = " + y);
}

Categories