I am still new to java and I've been trying to make a SpaceInvaders copy in Java's native graphics. I've finished the basic mechanics, however the game slows down significantly when the player or aliens shoot a bullet. I have tried to find out what was causing the game to slow down, but was unable to.
public class Board extends JPanel implements KeyListener,ActionListener{
Ship ship;
Alien[] row1 = new Alien[10];
Alien[] row2 = new Alien[10];
Alien[] row3 = new Alien[10];
private Timer timer;
int DELAY = 16;
boolean reachedend = false;
Bullet bullet;
int lives;
public Board() {
setBackground(Color.BLACK);
addKeyListener(this);
lives = 3;
ship = new Ship();
fillAliens();
timer = new Timer(DELAY, this);
timer.start();
}
void fillAliens() {
for(int x=1;x<11;x++) {
row1[x-1] = new Alien(x*30+40,30);
row2[x-1] = new Alien(x*30+40,70);
row3[x-1] = new Alien(x*30+40,110);
}
}
void shoot() {
if(bullet==null) {
bullet = new Bullet(ship.x + ship.width/2,ship.y - ship.height/2,-1);
}
}
void drawAliens(Graphics2D g) {
g.setColor(Color.red);
for(int x=1;x<11;x++) {
if(row1[x-1].alive == true) {
g.fillRect(row1[x-1].x_loc, row1[x-1].y_loc, row1[x-1].width, row1[x-1].width);
}
if(row2[x-1].alive == true) {
g.fillRect(row2[x-1].x_loc, row2[x-1].y_loc, row2[x-1].width, row2[x-1].width);
}
if(row3[x-1].alive == true) {
g.fillRect(row3[x-1].x_loc, row3[x-1].y_loc, row3[x-1].width, row2[x-1].width);
}
}
}
public void addNotify() {
super.addNotify();
requestFocus();
}
void drawShip(Graphics2D g) {
g.fillRect(ship.x, ship.y, ship.width, ship.height);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(lives>0) {
if (key == KeyEvent.VK_SPACE) {
shoot();
}
if (key == KeyEvent.VK_LEFT) {
if(ship.x>=5) {
ship.x -= 5;
}
}
if (key == KeyEvent.VK_RIGHT) {
if(ship.x+ship.width<434) {
ship.x += 5;
}
}
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShip(g2);
drawAliens(g2);
drawBullet(g2);
drawAlienBullet(g2);
drawLives(g2);
}
private void drawLives(Graphics2D g2) {
g2.setColor(Color.white);
g2.drawString("Lives:", 10, 300);
for(int x=1; x<=lives;x++) {
g2.fillRect(15*x+30, 290, 10, 10);
}
}
private void drawBullet(Graphics2D g2) {
g2.setColor(Color.GREEN);
if(bullet!=null) {
g2.fillRect(bullet.x_loc, bullet.y_loc, bullet.width, bullet.height);
}
}
private void drawAlienBullet(Graphics2D g2) {
g2.setColor(Color.BLUE);
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
g2.fillRect(row3[x].bullet.x_loc, row3[x].bullet.y_loc, row3[x].bullet.width, row3[x].bullet.height);
}
if(row2[x].bullet != null) {
g2.fillRect(row2[x].bullet.x_loc, row2[x].bullet.y_loc, row2[x].bullet.width, row2[x].bullet.height);
}
if(row1[x].bullet != null ) {
g2.fillRect(row1[x].bullet.x_loc, row1[x].bullet.y_loc, row1[x].bullet.width, row1[x].bullet.height);
}
}
}
private void bulletHitPlayer() {
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
if(row3[x].bullet.y_loc >= 350) {
row3[x].bullet = null;
break;
}
}
if(row2[x].bullet != null) {
if(row2[x].bullet.y_loc >= 350) {
row2[x].bullet = null;
break;
}
}
if(row1[x].bullet != null) {
if(row1[x].bullet.y_loc >= 350) {
row1[x].bullet = null;
break;
}
}
if(row3[x].bullet != null && row3[x].bullet.y_loc + 10 >= ship.y && row3[x].bullet.y_loc <= ship.y + ship.height && row3[x].bullet.x_loc >= ship.x && row3[x].bullet.x_loc <= ship.x+ship.width) {
row3[x].bullet = null;
lives--;
break;
}
if(row2[x].bullet != null && row2[x].bullet.y_loc + 10 >= ship.y && row2[x].bullet.y_loc <= ship.y + ship.height && row2[x].bullet.x_loc >= ship.x && row2[x].bullet.x_loc <= ship.x+ship.width) {
row2[x].bullet = null;
lives--;
break;
}
if(row1[x].bullet != null && row1[x].bullet.y_loc + 10 >= ship.y && row1[x].bullet.y_loc <= ship.y + ship.height && row1[x].bullet.x_loc >= ship.x && row1[x].bullet.x_loc <= ship.x+ship.width) {
row1[x].bullet = null;
lives--;
break;
}
}
}
private void bulletHit() {
if(bullet!=null) {
for(int x=0;x<10;x++) {
if(row3[x].alive == true && bullet.y_loc >= row3[x].y_loc && bullet.y_loc <= row3[x].y_loc+row3[x].width && bullet.x_loc >= row3[x].x_loc && bullet.x_loc <= row3[x].x_loc+row3[x].width) {
row3[x].alive = false;
bullet=null;
break;
}
if(row2[x].alive == true && bullet.y_loc >= row2[x].y_loc && bullet.y_loc <= row2[x].y_loc+row2[x].width && bullet.x_loc >= row2[x].x_loc && bullet.x_loc <= row2[x].x_loc+row2[x].width) {
row2[x].alive = false;
bullet=null;
break;
}
if(row1[x].alive == true && bullet.y_loc >= row1[x].y_loc && bullet.y_loc <= row1[x].y_loc+row1[x].width && bullet.x_loc >= row1[x].x_loc && bullet.x_loc <= row1[x].x_loc+row1[x].width) {
row1[x].alive = false;
bullet=null;
break;
}
}
}
if(bullet!=null) {
if(bullet.y_loc<0) {
bullet=null;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
}
}
Problem:
You draw your scene, whenever you press a key; and you draw your scene once on startup (see API and Tutorials) - But you should continuously redraw your scene by using the Timer properly.
How to solve:
When you create your Timer let it
either repeat itself timer.setRepeats(true);
or restart the Timer manually:
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
timer.restart(); //manually restart the timer
}
I am trying to replicate this code that I did in the console in GUI.
if (age <18 && feelings.toUpperCase().equals("SAD")){
System.out.println(phrase.sadQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("SAD") ) {
System.out.println(phrase.sadQuotesAfter18[rand.nextInt(3)]);
} else if (age <18 && feelings.toUpperCase().equals("ANGRY")){
System.out.println(phrase.angryQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("ANGRY")){
System.out.println(phrase.angryQuotesAfter18[rand.nextInt(8)]);
} else if (age < 18 && feelings.toUpperCase().equals("HAPPY")){
System.out.println(phrase.happyQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("HAPPY")){
System.out.println(phrase.happyQuotesAfter18[rand.nextInt(4)]);
} else {
System.out.println("You have entered and unknown combination, please try again");
}
As shown below. I realise in the code below I cannot get the else if and else statements as shown above to work. Only the if statement as shown below works. I am new to this so any assistance would be appreciated.
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (agebox.getText().equals("<=18") && feelings.equals("Sad")) {
}
showAlert(AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Your Quote!", phrase.sadQuotesBefore18[rand.nextInt(3)]);
}
}
not sure what is your problem, but at least you can categorize your if statements:
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String quoteStr="";
if (agebox.getText().equals("<18")) {
if (feelings.equals("SAD")) {
quoteStr = phrase.sadQuotesBefore18[rand.nextInt(3)];
} else if (feelings.equals("ANGRY")) {
quoteStr = phrase.angryQuotesBefore18[rand.nextInt(2)];
} else if (feelings.equals("HAPPY")) {
quoteStr = phrase.angryQuotesBefore18[rand.nextInt(2)];
}
}
else if (agebox.getText().equals(">=18")) {
if (feelings.equals("SAD")) {
quoteStr = phrase.sadQuotesAfter18[rand.nextInt(3)];
} else if (feelings.equals("ANGRY")) {
quoteStr = phrase.angryQuotesAfter18[rand.nextInt(8)];
} else if (feelings.equals("HAPPY")) {
quoteStr = phrase.angryQuotesAfter18[rand.nextInt(4)];
}
}
showAlert(AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Your Quote!", quoteStr);
}
}
I am creating a Binding of Isaac-esque Roguelike that is generated using an Array List using four Booleans. The four Booleans being North, East, South, and West. Corresponding to which doors is open.
The problem with Array Lists is that it can 'overlap'. For example, if I go east, than south, than west, than north, I'll be in a whole new room, and not the original.
Is there a way to stop this from happening, or at least prevent it? Such as if the room above room 1 (room 2) has south set to true, than north will be true in room 1 to connect the two rooms. Or if room 2 has south set to false, than north will be false in room 1 to stop overlap.
Here is my current code (I know my code isn't exactly clean and has a lot of magic numbers, but those shouldn't be important for this question)-
GameState:
public class GameState extends JFrame implements KeyListener {
Container contentPane=this.getContentPane();
Graphics bufferGraphics;
int characterX=463;
int characterY=486;
int oldCharacterX=463;
int oldCharacterY=486;
int xAxis;
int yAxis;
int minimapX=1300;
int minimapY=515;
Image characterNorth = CustomImages.createImageIcon("Images/characterNorth.jpg").getImage();
Image characterEast = CustomImages.createImageIcon("Images/characterEast.jpg").getImage();
Image characterSouth = CustomImages.createImageIcon("Images/characterSouth.jpg").getImage();
Image characterWest = CustomImages.createImageIcon("Images/characterWest.jpg").getImage();
Image brickWall = CustomImages.createImageIcon("Images/brickWall.jpg").getImage();
Image brickFloor = CustomImages.createImageIcon("Images/brickFloor.jpg").getImage();
Image character=characterNorth;
boolean pressed=false;
boolean minimap=true;
ArrayList<RoomState> map = new ArrayList<RoomState>();
RoomState currentRoom = new RoomState();
RoomState currentRoomState=new RoomState();
GameState() {
this.setBounds(0, 0, 1680, 1050);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void move(int x, int y) { //Check Move
currentRoomState=currentRoomState.MoveToNextRoom(true, false, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, true, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, true, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, false, true);
}
public void paint(Graphics g) { //Graphics
for(xAxis=58;xAxis<=858;xAxis=xAxis+50) {
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickFloor,xAxis,yAxis,null);
}
yAxis=31;
}
for(xAxis=8;xAxis<958;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
yAxis=931;
for(xAxis=8;xAxis<=908;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=8;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=908;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
if(currentRoom.northDoor) {
g.drawImage(brickFloor,458,31,null);
}
if(currentRoom.eastDoor) {
g.drawImage(brickFloor,908,481,null);
}
if(currentRoom.southDoor) {
g.drawImage(brickFloor,458,931,null);
}
if(currentRoom.westDoor) {
g.drawImage(brickFloor,8,481,null);
}
g.drawImage(character,characterX,characterY,null);
g.drawString("[ ]",minimapX,minimapY);
g.setColor(Color.RED);
g.drawString("[ ]", 1300, 515);
}
#Override
public void keyPressed(KeyEvent arg0) { //Character Rotation/Movement.
if(pressed==false) {
pressed=true;
oldCharacterX=characterX;
oldCharacterY=characterY;
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
if(character==characterNorth) {
if(characterY>86 && characterX>13 && characterX<913) {
characterY=characterY-50;
}else if(currentRoom.northDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY-50;
if(characterY==-14) {
if(currentRoom.rs_NorthDoor != null) {
currentRoom=currentRoom.rs_NorthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, true, false);
currentRoom.rs_NorthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY-10;
characterX=463;
characterY=936;
repaint();
}
}
}else {
character=characterNorth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(character==characterWest && characterY>36 && characterY<926) {
if(characterX>63) {
oldCharacterX=characterX;
characterX=characterX-50;
}else if(currentRoom.westDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX-50;
if(characterX==-37) {
if(currentRoom.rs_WestDoor != null) {
currentRoom = currentRoom.rs_WestDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, true, false, false);
currentRoom.rs_WestDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX-8;
characterX=913;
characterY=486;
repaint();
}
}
}else {
character=characterWest;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(character==characterSouth) {
if(characterY<871 && characterX>13 && characterX<913) {
oldCharacterY=characterY;
characterY=characterY+50;
}else if(currentRoom.southDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY+50;
if(characterY==986) {
if(currentRoom.rs_SouthDoor != null) {
currentRoom=currentRoom.rs_SouthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,true, false, false, false);
currentRoom.rs_SouthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY+10;
characterX=463;
characterY=36;
repaint();
}
}
}else {
character=characterSouth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(character==characterEast && characterY>36 && characterY<926) {
if(characterX<848) {
oldCharacterX=characterX;
characterX=characterX+50;
}else if(currentRoom.eastDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX+50;
if(characterX==963) {
if(currentRoom.rs_EastDoor != null) {
currentRoom = currentRoom.rs_EastDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, false, true);
currentRoom.rs_EastDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX+8;
characterX=13;
characterY=486;
repaint();
}
}
}else {
character=characterEast;
}
}
if(oldCharacterX != characterX || oldCharacterY != characterY) {
repaint(oldCharacterX,oldCharacterY,40,40);
}
repaint(characterX,characterY,40,40);
}
}
#Override
public void keyReleased(KeyEvent arg0) { //Prevents Holding Down Keys.
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
pressed=false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
RoomState:
public class RoomState {
boolean northDoor;
boolean eastDoor;
boolean southDoor;
boolean westDoor;
boolean doorsOpen;
int northRoll;
int eastRoll;
int southRoll;
int westRoll;
Random r=new Random();
//Reference to the adjacent rooms
RoomState rs_NorthDoor=null;
RoomState rs_EastDoor=null;
RoomState rs_SouthDoor=null;
RoomState rs_WestDoor=null;
RoomState() { //Initial
while(!doorsOpen) {
northRoll=r.nextInt(6)+1;
eastRoll=r.nextInt(6)+1;
southRoll=r.nextInt(6)+1;
westRoll=r.nextInt(6)+1;
if(northRoll==1) {
northDoor=true;
}else {
northDoor=false;
}
if(eastRoll==1) {
eastDoor=true;
}else {
eastDoor=false;
}
if(southRoll==1) {
southDoor=true;
}else {
southDoor=false;
}
if(westRoll==1) {
westDoor=true;
}else {
westDoor=false;
}
if(northDoor==false && eastDoor==false && southDoor==false && westDoor==false) {
doorsOpen=false;
}else {
doorsOpen=true;
}
}
}
RoomState(RoomState previousState, boolean north, boolean east, boolean south, boolean west) {
this();
if(north) {
rs_NorthDoor=previousState;
northDoor=true;
}else if(east) {
rs_EastDoor=previousState;
eastDoor=true;
}else if(south) {
rs_SouthDoor=previousState;
southDoor=true;
}else if(west) {
rs_WestDoor=previousState;
westDoor=true;
}
}
public RoomState MoveToNextRoom(boolean north, boolean east, boolean south, boolean west) {
if(north) {
if(rs_NorthDoor==null) {
rs_NorthDoor=new RoomState(this,north,east,south,west);
}
return rs_NorthDoor;
}
if(east) {
if(rs_EastDoor==null) {
rs_EastDoor=new RoomState(this,north,east,south,west);
}
return rs_EastDoor;
}
if(south) {
if(rs_SouthDoor==null) {
rs_SouthDoor=new RoomState(this,north,east,south,west);
}
return rs_SouthDoor;
}
if(west) {
if(rs_WestDoor==null) {
rs_WestDoor=new RoomState(this,north,east,south,west);
}
return rs_WestDoor;
}
return null;
}
}
Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}
I have written a method checkState() which takes the argument JButton[][] which is a 2-D array of buttons and returns the state of the button matrix. However, it is showing this error when I am trying to invoke it in the anonymous inner class of ActionPerformed. Could you help me with the reason behind the error?
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class PlayGameUU
{
int moves=0;
String s;
public PlayGameUU(JButton[][] box)
{
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
box[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
while (checkState(box)==0)
{
if (((JButton)e.getSource()).getText().equals(""))
{
if (moves%2==0)
{
((JButton)e.getSource()).setText("0");
moves++;
}
else
{
((JButton)e.getSource()).setText("X");
moves++;
}
}
}
if (checkState(box)==1)
s="0 wins";
else if (checkState(box)==2)
s="X wins";
else if (checkState(box)==3)
s="Tie";
}});
}
}
}
final public int checkState(JButton[][] box)
//Returns 1 for zero win, 2 for cross win and 3 for draw, 0 otherwise
{
int flagzerowin=0;
int flagcrosswin=0;
for (int row=0;row<3;row++)
{
if (box[row][0].getText().equals("X") && box[row] [1].getText().equals("X") && box[row][2].getText().equals("X"))
{
flagcrosswin=1;
break;
}
else if (box[row][0].getText().equals("0") &&box[row][1].getText().equals("0") &&box[row][2].getText().equals("0"))
{
flagzerowin=1;
break;
}
}
for (int col=0;col<3;col++)
{
if (box[0][col].getText().equals("X") &&box[1][col].getText().equals("X") &&box[2][col].getText().equals("X"))
{
flagcrosswin=1;
break;
}
else if (box[0][col].getText().equals("0") &&box[1][col].getText().equals("0") &&box[2][col].getText().equals("0"))
{
flagzerowin=1;
break;
}
}
if (box[0][0].getText().equals("X") && box[1][1].getText().equals("X") && box[2][2].getText().equals("X"))
flagcrosswin=1;
if (box[0][2].getText().equals("X") && box[1][1].getText().equals("X") && box[2][0].getText().equals("X"))
flagcrosswin=1;
if (box[0][0].getText().equals("0") && box[1][1].getText().equals("0") && box[2][2].getText().equals("0"))
flagzerowin=1;
if (box[0][2].getText().equals("0") && box[1][1].getText().equals("0") && box[2][0].getText().equals("0"))
flagzerowin=1;
if (flagzerowin==1)
return (1);
else if (flagcrosswin==1)
return(2);
int flagfull=1;
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
if (box[i][j].getText().equals(""))
flagfull=0;
}
}
if ((flagzerowin==0)&&(flagcrosswin==0)&&(flagfull==1))
return(3); //Draw
else
return (0);
}
}
Here is the code where the PlayGameUU constructor gets called:
public JButton box[][]=new JButton[3][3];
public int mode;
if (mode==1)
{
new PlayGameUU(box);
}