Delaying Attacks With TimerTask Not Working Well - java

I'm making a fighting game and I want the actions of the player to be timed so you can't spam the attack key and win easily.
Here is where I do the keyboard stuff and delay. It does delay the first time, but then it the delay slowly decreases in time and ends up being 0 and lets you spam the key. As you can see I've done many things to try and stop the key from registering in the delay etc.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isAction == false) {
if (key == KeyEvent.VK_LEFT) {
dx = -1;
if (nHeroX < -10) {
dx = 0;
}
isRight = false;
isMoving = true;
} else if (key == KeyEvent.VK_RIGHT) {
dx = 1;
if (nHeroX > 1200) {
dx = 0;
}
isRight = true;
isMoving = true;
} else if (key == KeyEvent.VK_C) {
dx = 0;
isAction = true;
isMoving = false;
isBlock = true;
nImage = 1;
} else if (key == KeyEvent.VK_X) {
dx = 0;
isAction = true;
isMoving = false;
isWeak = true;
nImage = 2;
} else if (key == KeyEvent.VK_Z) {
dx = 0;
isAction = true;
isMoving = false;
isStrong = true;
nImage = 3;
} else if (key == KeyEvent.VK_P) {
if (!pause) {
pause = true;
} else if (pause) {
pause = false;
}
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
dx = 0;
isMoving = false;
nState = nImage = 1;
} else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
delayTask = new DelayTask();
tmrDelay.schedule(delayTask, 0, 500);
} else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
z = new DelayTask();
tmrDelay.schedule(z, 0, 450);
} else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
x = new DelayTask();
tmrDelay.schedule(x, 0, 1200);
}
nImgNum = (int) (Math.random() * 6 + 1);
nDelay = 0;
}
//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {
public int nTimes = 0;
#Override
public void run() {
nTimes++;
if (nTimes == 2) {
isAction = isBlock = isStrong = isWeak = false;
nState = nImage = 1;
}
}
}
Can someone explain why my delay is messed up? Thank you.
Also this code:
private class Keys extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
hero.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
hero.keyReleased(e);
if (hero.getPause()) {
repaint();
}
}
}

The simplest way to do this is just to remember the last time.
So:
private long lastTime = 0;
void doAction() {
long timeNow = System.currentTimeMillis()
if (lastTime + MIN_DELAY < timeNow) {
return;
}
lastTime = timeNow;
// Do action
}
All the stuff with timers etc is just approaching this from a much more complicated architecture than you need to.

Related

make players change after certain time in java

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

Implementing a game menu in processing3

I am making a little game for my university coursework and got stuck at the menu creation. Been trying to solve this for a while. Here goes the code:
Before trying to fiddle around the loop and noLoop() functions and before I moved the arrow placement from void setup to void keypressed my game has worked. Now the program freezes before running draw.
What I want is to only display the menu background before the key, in this case s for start, has been pressed. If anyone could come up with some directions it would be of a great help.
Thanks in advance.
int totalArrows = 6;
arrowclass[] theArrows = new arrowclass[totalArrows];
PImage[] imgList = new PImage[4];
PImage bg;
PImage life;
PImage menu;
int score;
int loose = 3;
void setup() {
size(400, 600);
bg = loadImage("bck.jpg");
life = loadImage("life.png");
menu = loadImage("menu.jpg");
background(menu);
// loading the arrow imgs
for (int i= 0; i<4; i++) {
println(i+".png");
imgList[i] = loadImage(i+".png");
}
noLoop();
}
void draw() {
textSize(32);
text(score,30,100);
// active area
fill(255,31,31);
rect(0,500,width,100);
//lifetrack
if (loose==3){
image(life,10,10);
image(life,45,10);
image(life,80,10);
}
if (loose==2){
image(life,10,10);
image(life,45,10);
}
if (loose==1){
image(life,10,10);
}
// calling class action, movement
for (int i = 0; i<totalArrows; i++) {
theArrows[i].run();
if (theArrows[i].y>475 && theArrows[i].y<600) {
theArrows[i].inactive = true;
}
if(theArrows[i].did == false && theArrows[i].y>598) {
theArrows[i].lost = true;
}
if(theArrows[i].lost && theArrows[i].did == false && theArrows[i].wrongclick == false){
loose--;
theArrows[i].lost = false;
}
}
if (loose == 0){
textSize(32);
text("gameover",width/2,height/2);
for(int i=0; i<totalArrows;i++){
}
}
}
void keyPressed() {
if (key == 'p'){
// placing tha arrows. (i*105 = positioning) THIS PART IS AN ISSUE FOR SURE. SEE ARROW CLASS
for (int i= 0; i<totalArrows; i++) {
theArrows[i] = new arrowclass(-i*105);
}
loop();
}
}
void keyReleased() {
for (int i= 0; i<totalArrows; i++) {
if (theArrows[i].inactive && theArrows[i].did == false) {
if (keyCode == UP && theArrows[i].id == 3){
score++;
theArrows[i].did = true;
}
if (keyCode != UP && theArrows[i].id == 3){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == DOWN && theArrows[i].id == 0){
score++;
theArrows[i].did = true;
}
if (keyCode != DOWN && theArrows[i].id == 0){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == RIGHT && theArrows[i].id == 2){
score++;
theArrows[i].did = true;
}
if (keyCode != RIGHT && theArrows[i].id == 2){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == LEFT && theArrows[i].id == 1){
score++;
theArrows[i].did = true;
}
if (keyCode != LEFT && theArrows[i].id == 1){
loose--;
theArrows[i].wrongclick = true;
}
}
}
}
And the arrow class:
class arrowclass{
int y;
int id;
boolean did;
boolean inactive;
boolean lost;
boolean wrongclick;
// proprieties of the class
arrowclass(int initY){
y = initY;
id = int(random(4));
did = false;
inactive = false;
lost = false;
wrongclick = false;
}
//actions
void run(){
image(imgList[id],width/2,y);
// score goes up, speed goes up
y += 2+score;
// reset arrow to default
if (y>600) {
y = -50;
id = int(random(4));
inactive = false;
did = false;
lost = false;
wrongclick = false;
}
}
}

Graphics g/ KeyEvent e incompatibility

When I attempt to draw the objects in the array it successfully displays them if there is no KeyEvent e in the header, but if KeyEvent e is in the header like is shown (and to my knowledge it needs to be in order to call the method) it does not print anything out.
How can I use the method I created that moves an object in the array if I cannot have KeyEvent e in the header?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Field extends Applet
{
public void paint(Graphics g, KeyEvent e)
{
drawField(g,e);
}
public void drawField(Graphics g, KeyEvent e)
{
int Field[][] = new int[1000][1000];
int Roadl[][] = new int[1000][1000];
Field[100][100] = 1;
Field[100][300] = 2;
Field[100][500] = 3;
Roadl[100][500] = 500;
Field[300][100] = 4;
Roadl[300][100] = 500;
Field[600][600] = 6;
moveCar(Field,600,600,e);
for(int i = 0; i < Field.length; i++)
{
for (int k = 0; k < Field[i].length; k++)
{
if (Field[i][k] == 1)
{
VertBuilding vb1 = new VertBuilding(i,k,g);
}
else if (Field[i][k] == 2)
{
HorizBuilding hb1 = new HorizBuilding(i,k,g);
}
else if (Field[i][k] == 3)
{
VertRoad vr1 = new VertRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 4)
{
HorizRoad hr1 = new HorizRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 5)
{
Coin c1 = new Coin(i,k,g);
}
else if (Field[i][k] == 6)
{
HorizCar car1 = new HorizCar(i,k,g);
}
else if (Field[i][k] == 7)
{
VertCar car1 = new VertCar(i,k,g);
}
}
}
}
public void moveCar(int[][] arr1, int i, int k, KeyEvent e)
{
i += keyTypedH(e);
k += keyTypedV(e);
arr1[i][k] = carD(e);
}
public int keyTypedV (KeyEvent e) {
char c = e.getKeyChar();
int y = 0;
if (c == 's')
{
y+=10;
}
else if (c == 'w')
{
y-=10;
}
return y;
}
public int keyTypedH (KeyEvent e) {
char c = e.getKeyChar();
int x = 0;
if (c == 'a')
{
x-=10;
}
else if (c == 'd')
{
x+=10;
}
return x;
}
public int carD (KeyEvent e) {
char c = e.getKeyChar();
int carLocation = 0;
if (c == 'a')
{
carLocation = 6;
}
else if (c == 'd')
{
carLocation = 6;
}
else if (c == 's')
{
carLocation = 7;
}
else if (c == 'w')
{
carLocation = 7;
}
return carLocation;
}
}

Minimax algorithm always returns one number

I have got a problem with minimax algorithm. I want to make tic tac toe game with AI. I used JFrame to make that.
So my minimax algorithm returns always number 9 and I don't know why. What's wrong ?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Zadanie2 extends JFrame implements ActionListener {
/**
*
*/
JButton button0 = new JButton("");
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
int playerSign = 1;
String computerMark, opponentMark;
public static final long serialVersionUID = 1L;
JButton[] buttonArray = { button0, button1, button2, button3, button4,
button5, button6, button7, button8, button9 };
Object[] options = { "GRAJ OD NOWA", "ZAKOŃCZ GRĘ" };
Object[] startOptions = { "GRACZ", "KOMPUTER", "OPUŚĆ GRĘ" };
boolean canMove;
boolean computerStarted;
int bb = 1;
public Zadanie2() {
super("KÓŁKO I KRZYŻYK");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setResizable(false);
setLocation(470,400);
setLayout(new GridLayout(3,3));
for(int i = 1; i <= 9; i++){
add(add(buttonArray[i]));
buttonArray[i].addActionListener(this);
}
setVisible(true);
int y = JOptionPane.showOptionDialog(null,"WYBIERZ KTO MA ZACZĄĆ GRĘ","WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE,
null,
startOptions,
startOptions[0]);
if (y == 2) {
System.exit(1);
}
if (y == 1) { // COMPUTER
computerStarted = true;
computerMark = "X";
opponentMark = "O";
canMove = true;
computerMove();
}
if (y == 0) { // PLAYER
computerStarted = false;
computerMark = "O";
opponentMark = "X";
}
}
public static void main(String[] args) {
new Zadanie2();
}
public void close() {
playerSign = 1;
dispose();
}
private void computerMove() {
if(canMove){
System.out.println("AI: "+AI(buttonArray));
buttonArray[AI(buttonArray)].doClick();
}
canMove = false;
}
private int AI(JButton[] buttonArray2){
int ruch, i, m, mmx;
ruch = 0;
mmx = -10;
for(i = 1; i < 9; i++)
if(buttonArray[i].getText() == "");
{
buttonArray[i].setText(computerMark);
m = minimax(buttonArray, computerMark);
buttonArray[i].setText("");
if (m > mmx) {
mmx = m;
ruch = i;
}
}
return ruch;
}
public int minimax(JButton[] buttonArray,String gracz){
int m, mmx;
if(win(buttonArray,gracz)) return (gracz == computerMark) ? 1 : -1;
if(tie(buttonArray)){
return 0;}
gracz = (gracz == computerMark) ? opponentMark : computerMark;
mmx = (gracz == opponentMark) ? 10 : -10;
for(int i = 1; i <= 9; i++)
if(buttonArray[i].getText() == "")
{
buttonArray[i].setText(gracz);
m = minimax(buttonArray,gracz);
buttonArray[i].setText("");
if(((gracz == opponentMark) && (m < mmx)) || ((gracz == computerMark) && (m > mmx))){mmx = m;}
}
return mmx;
}
private void checkWin() {
if(win(buttonArray,"X")){
winX();
}
if(win(buttonArray,"O")){
winO();
}
if(tie(buttonArray)){
sayTie();
}
}
private void winX() {
int n = JOptionPane.showOptionDialog(null, "WYGRAŁ GRACZ X ",
"WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
private void winO() {
int n = JOptionPane.showOptionDialog(null, "WYGRAŁ GRACZ O ",
"WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
private void sayTie() {
int n = JOptionPane.showOptionDialog(null, "REMIS! ", "WIADOMOŚĆ",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
public boolean tie(JButton[] buttonArray2){
for(int i = 1; i <= 9; i++){
if(buttonArray2[i].getText() == ""){
return false;
}
}
return true;
}
private boolean win(JButton[] buttonArray2, String g) {
if (buttonArray2[1].getText() == buttonArray2[2].getText()
&& buttonArray2[1].getText() == buttonArray2[3].getText()
&& buttonArray2[2].getText() == buttonArray2[3].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[3].getText() == buttonArray2[7].getText()
&& buttonArray2[3].getText() == buttonArray2[5].getText()
&& buttonArray2[7].getText() == buttonArray2[5].getText() && buttonArray2[3].getText() == g) {
return true;
}
if (buttonArray2[7].getText() == buttonArray2[8].getText()
&& buttonArray2[7].getText() == buttonArray2[9].getText()
&& buttonArray2[8].getText() == buttonArray2[7].getText() && buttonArray2[7].getText() == g) {
return true;
}
if (buttonArray2[4].getText() == buttonArray2[5].getText()
&& buttonArray2[4].getText() == buttonArray2[6].getText()
&& buttonArray2[5].getText() == buttonArray2[6].getText() && buttonArray2[4].getText() == g) {
return true;
}
if (buttonArray2[1].getText() == buttonArray2[5].getText()
&& buttonArray2[1].getText() == buttonArray2[9].getText()
&& buttonArray2[5].getText() == buttonArray2[9].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[1].getText() == buttonArray2[4].getText()
&& buttonArray2[1].getText() == buttonArray2[7].getText()
&& buttonArray2[4].getText() == buttonArray2[7].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[2].getText() == buttonArray2[8].getText()
&& buttonArray2[2].getText() == buttonArray2[5].getText()
&& buttonArray2[8].getText() == buttonArray2[5].getText() && buttonArray2[2].getText() == g) {
return true;
}
if (buttonArray2[3].getText() == buttonArray2[6].getText()
&& buttonArray2[3].getText() == buttonArray2[9].getText()
&& buttonArray2[6].getText() == buttonArray2[9].getText() && buttonArray2[3].getText() == g) {
return true;
}
return false;
};
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 1; i <= 9; i++) {
if (source == buttonArray[i] ) {
playerSign++;
if (playerSign % 2 == 0 && buttonArray[i].getText() == "") {
buttonArray[i].setText("X");
}
if (playerSign % 2 != 0 && buttonArray[i].getText() == "") {
buttonArray[i].setText("O");
}
if (computerStarted && playerSign % 2 != 0) {
canMove = true;
computerMove();
}
if (!computerStarted && playerSign % 2 == 0) {
canMove = true;
computerMove();
}
}
}
System.out.println("PS: " + playerSign);
if(playerSign > 3){
checkWin();}
}
}
Any ideas on how I may solve this problem?
You should use .equals instead of == whenever you compare two Objects.
E.g. there should be computerMark.equals(gracz) instead of gracz == computerMark.
Edit:
Also, You should replace 1 and -1 with 10 and -10 respectively here:
if(win(buttonArray,gracz)) return (gracz == computerMark) ? 1 : -1;
Reference

Java connect four victory check

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.

Categories