This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Everybody!
I'm here to annoy you once more)
So, I was trying to make a game, I described some classes:
GameObject - just an object which has X,Y,Sizes,Name and may be drawn and moved:
package pkg3dgraphics;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class GameObject {
protected String name;
protected int xCoord,yCoord,mySizeX = 25,mySizeY = 25;
public GameObject(){
}
public GameObject(String newName, int startXCoord, int startYCoord){
setName(newName);
setX(startXCoord);
setY(startYCoord);
}
public void SetSize(int X, int Y){
mySizeX = X;
mySizeY = Y;
}
public int getXsize(){
return mySizeX;
}
public int getYsize(){
return mySizeY;
}
public String getName(){
return name;
}
public void setName(String newName){
name = newName;
}
public int getX(){
return xCoord;
}
public int getY(){
return yCoord;
}
public void setX(int newXCoord){
xCoord = newXCoord;
}
public void setY(int newYCoord){
yCoord = newYCoord;
}
public void moveTo(int X,int Y){
xCoord = X;
yCoord = Y;
}
public void moveBy(int X,int Y){
xCoord +=X;
yCoord +=Y;
}
public void Draw(GraphicsContext currentContext){
currentContext.setFill(Color.GREEN);
currentContext.setStroke(Color.BLUE);
currentContext.fillOval(xCoord,yCoord, mySizeX,mySizeY );
}
}
And I have Shooter extending previous class and here he goes:
package pkg3dgraphics;
public class Shooter extends GameObject {
public Shooter(){
}
public Shooter(String newName, int startXCoord, int startYCoord){
setName(newName);
setX(startXCoord);
setY(startYCoord);
}
public Bullet shoot(String direction){
Bullet newBullet = new Bullet(direction);
return newBullet;
}
}
Also I've got Bullets which are , you know, bullets:
package pkg3dgraphics;
import javafx.scene.paint.Color;
import javafx.scene.canvas.GraphicsContext;
public class Bullet extends GameObject{
String myDirection;
protected int mySpeed = 5,mySizeX = 5,mySizeY = 5;
boolean goNorth,goSouth,goWest,goEast;
protected boolean active = false;
public void setSpeed(int newSpeed){
mySpeed = newSpeed;
}
public void setDirection(String newDirection){
myDirection = newDirection;
active = true;
if ( myDirection == "North" )
goNorth = true;
if ( myDirection == "South" )
goSouth = true;
if ( myDirection == "West" )
goWest = true;
if ( myDirection == "East" )
goEast = true;
}
Bullet(String direction ){
myDirection = direction;
active = true;
if ( myDirection == "North" )
goNorth = true;
if ( myDirection == "South" )
goSouth = true;
if ( myDirection == "West" )
goWest = true;
if ( myDirection == "East" )
goEast = true;
}
public void advance(int W,int H,GraphicsContext gc){
if (xCoord <= W && xCoord >= 0 && yCoord <= H && yCoord >= 0 ) {
if (goNorth) moveBy(0,mySpeed);
if (goSouth) moveBy(0,mySpeed);
if (goWest) moveBy(mySpeed,0);
if (goEast) moveBy(mySpeed,0);
}else{
active = false;
Vanish(gc);
goNorth = false;
goSouth = false;
goWest = false;
goEast = false;
}
}
public void Vanish(GraphicsContext gc){
gc.setFill(Color.WHITE);
}
}
The purpose was to have this guy shooting in a next way:
When I catch pressed button I use precreated inactive bullet and direct it to go in a several direction.
When this bullet crosses a window's border it becomes inactive and stops.
For this I have an array of Bullets.
When user presses shoot key I seek in the array for an inactive Bullet and if there is none I create additional one which follows the path user wanted.
Well, this way to Implement bullets probably is not the best, but I didn't come up with another.
So I compiled my Main Class:
package pkg3dgraphics;
import java.util.Vector;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import static javafx.scene.input.KeyCode.DOWN;
import static javafx.scene.input.KeyCode.LEFT;
import static javafx.scene.input.KeyCode.RIGHT;
import static javafx.scene.input.KeyCode.SHIFT;
import static javafx.scene.input.KeyCode.UP;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
public int WINDOWWIDTH = 600;
public int WINDOWHEIGHT = 400;
boolean goNorth,goSouth,goWest,goEast,running,ShootNorth,ShootSouth,ShootWest,ShootEast;
Shooter player = new Shooter("Player",WINDOWWIDTH/2,WINDOWHEIGHT/2);
Bullet bullets[] = new Bullet[500];
int bulletsSize = 0;
Canvas mainCanvas = new Canvas(WINDOWWIDTH,WINDOWHEIGHT);
GraphicsContext mainContext = mainCanvas.getGraphicsContext2D();
#Override
public void start(Stage primaryStage) {
Group root = new Group();
Canvas mainCanvas = new Canvas(WINDOWWIDTH,WINDOWHEIGHT);
GraphicsContext mainContext = mainCanvas.getGraphicsContext2D();
root.getChildren().add(mainCanvas);
Scene scene = new Scene(root,WINDOWWIDTH,WINDOWHEIGHT);
scene.setOnKeyPressed(new EventHandler<KeyEvent> (){
#Override
public void handle(KeyEvent event){
switch(event.getCode()){
case UP: ShootNorth = true; break;
case DOWN: ShootSouth = true; break;
case LEFT: ShootWest = true; break;
case RIGHT: ShootEast = true; break;
case W: goNorth = true; break;
case S: goSouth = true; break;
case A: goWest = true; break;
case D: goEast = true; break;
}
}
});
scene.setOnKeyReleased(new EventHandler <KeyEvent>(){
#Override
public void handle(KeyEvent event){
switch(event.getCode()){
case UP: ShootNorth = false; break;
case DOWN: ShootSouth = false; break;
case LEFT: ShootWest = false; break;
case RIGHT: ShootEast = false; break;
case W: goNorth = false; break;
case S: goSouth = false; break;
case A: goWest = false; break;
case D: goEast = false; break;
}
}
});
primaryStage.setScene(scene);
primaryStage.show();
AnimationTimer Timer = new AnimationTimer(){
#Override
public void handle (long now){
int dx = 0, dy = 0;
if (goNorth) dy = -1;
if (goSouth) dy = 1;
if (goWest) dx = -1;
if (goEast) dx = 1;
if (running) { dx *= 3; dy *= 3;}
mainContext.clearRect(0,0,WINDOWWIDTH,WINDOWHEIGHT);
player.moveBy(dx, dy);
CheckShoot();
player.Draw(mainContext);
}
};
Timer.start();
}
public void CheckShoot(){
String direction = null;
int count = 0;
if (ShootNorth)
{
direction = "North";
}
if (ShootSouth)
{
direction = "South";
}
if (ShootWest)
{
direction = "West";
}
if (ShootEast)
{
direction = "East";
}
for (int i = 0; i < bulletsSize; i ++ )
{
if (bullets[i].active = false ){
bullets[i].setDirection(direction);
bullets[i].moveTo(player.getX(),player.getY());
break;
}else count ++;
}
if ( count == bulletsSize ) {
bulletsSize++;
bullets[bulletsSize] = player.shoot(direction);
}
}
public void advanceAll(){
for (int i = 0; i < bulletsSize; i ++ )
{
bullets[i].advance(WINDOWWIDTH,WINDOWHEIGHT,mainContext);
}
}
}
Application runs but then I get this problem looped untill I close the application:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at pkg3dgraphics.Main.CheckShoot(Main.java:126)
at pkg3dgraphics.Main$3.handle(Main.java:91)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.lambda$handle$483(AnimationTimer.java:57)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.handle(AnimationTimer.java:56)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:357)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:506)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
So, that is all I wanted to complain about.
If someone has any idea why these all occure I would be glad and grateful if you shared the secret with me.(And all others)
You seem to have created the array, without creating each members
Bullet bullets[] = new Bullet[500];
Then you iterate through them, while they are nulls
for (int i = 0; i < bulletsSize; i ++ )
{
if (bullets[i].active = false ){
bullets[i].setDirection(direction);
bullets[i].moveTo(player.getX(),player.getY());
break;
}else count ++;
}
bullets[i] = null, and you try to invoke .active on it.
Solution:
Try to check nulls
if (bullets[i] == null) { bullets[i] = new Bullet(); }
if (bullets[i].active = false ){
bullets[i].setDirection(direction);
bullets[i].moveTo(player.getX(),player.getY());
break;
}else count ++;
Read What is NullPointerException
Related
I have this array of classes extending JButtons, and when one is clicked it registers that.
Then if another one gets clicked, they should 'switch' places. So my question is: How can i implement it that is swiches the buttons (so far i got before) and (the important part) how can i 'refresh' the GUI, so the user can see the chenge visually. Following the code:
import javax.swing.*; import Pieces.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game extends JFrame {
private static final int width = 8;
private static final int height = 8;
private static Piece clicked;
public static Piece[][] fields = new Piece[width][height];
private JPanel main = new JPanel();
public static void init(JPanel g) {
for (int y = 0; y < fields.length; y++) {
for (int x = 0; x < fields[y].length; x++) {
if (y == 0) {
switch (x) {
case 0,7:
fields[y][x] = new Rook(x,y,1);
break;
case 1,6:
fields[y][x] = new Knight(x,y,1);
break;
case 2,5:
fields[y][x] = new Bishop(x,y,1);
break;
case 3:
fields[y][x] = new Queen(x,y,1);
break;
case 4:
fields[y][x] = new King(x,y,1);
break;
}
}
if (y == 1) fields[y][x] = new Pawn(x, y, 1);
else if (y >= 2 && y <= 5) fields[y][x] = new Empty(x,y,9);
else if (y == 6) fields[y][x] = new Pawn(x, y, 0);
else if(y == 7) {
switch (x) {
case 0,7:
fields[y][x] = new Rook(x,y,0);
break;
case 1,6:
fields[y][x] = new Knight(x,y,0);
break;
case 2,5:
fields[y][x] = new Bishop(x,y,0);
break;
case 3:
fields[y][x] = new Queen(x,y,0);
break;
case 4:
fields[y][x] = new King(x,y,0);
break;
}
}
fields[y][x].addActionListener(e -> {
var p = (Piece) e.getSource();
var pPos = p.getCell();
if(clicked == null) {
clicked = p;
System.out.println(fields[clicked.getCell().y][clicked.getCell().x]);
clicked.setForeground(Color.yellow.darker());
System.out.println("clicked " + pPos);
} else if (pPos == clicked.getCell()) {
clicked.setForeground(Color.white);
System.out.println("deselecting " + pPos);
clicked = null;
} else {
if (clicked.canMoveTo(fields, pPos)) {
fields[p.getCell().y][p.getCell().x] = clicked;
fields[clicked.getCell().y][clicked.getCell().x] = new Empty(clicked.getCell().x, clicked.getCell().y, 9);
System.out.println("moving " + clicked.getCell() + " to " + pPos);
clicked.setForeground(Color.white);
}
else System.out.println("canĀ“t move there, sry");
clicked = null;
}
SwingUtilities.updateComponentTreeUI(g);
});
g.add(fields[y][x]);
}
}
}
public Game() {
main.setBackground(Color.darkGray.darker());
main.setLayout(new GridLayout(8,8));
this.setSize(800,800);
init(main);
this.add(main);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
var g = new Game();
}
}
package Pieces;
import javax.swing.*;
import java.awt.*;
public abstract class Piece extends JButton {
private final int isWhite; //0 is false, 1 is true, 9 is undefined
private Point cell;
public Piece(int x, int y, int isWhite) {
cell = new Point(x, y);
this.isWhite = isWhite;
this.setForeground(Color.white);
this.setOpaque(false);
//this.setContentAreaFilled(false);
}
public Point getCell() {
return cell;
}
public int isWhite() {
return isWhite;
}
public boolean canMoveTo(Piece[][] fields, Point point) {
return true;
}
}
*all the pieces are setup like this
package Pieces;
public class Bishop extends Piece{
public Bishop(int x, int y, int isWhite) {
super(x, y, isWhite);
this.setText("Bishop");
}
}
(yee, this will hopefully be chess sometimes)
I am trying to make a snake JavaFX game. The scene is a board that consists of 25x25 images. For now, I just want to make the snake go to the right before I add userInput. The first scene is loading from Controller.java and then in Main.java, I am calling run_game() method (inside controller.java) which changes the scene every second. The issue is that the first scene shows up but the scene does not get updated. There is no error, the program just keeps running till I stop it.
Here are the classes:-
Main.java
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;
public class Main extends Application {
public Controller game;
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Snake Game");
game = new Controller();
primaryStage.setScene(game.scene);
primaryStage.show();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
try {
game.run_game();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},0,1000);
}
public static void main(String[] args) { launch(args); }
}
Controller.java
import javafx.animation.AnimationTimer;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import java.util.TimerTask;
public class Controller {
public Snake snake;
public Board board;
public Food food;
public Movement move;
public static GridPane grid_pane;
public Scene scene;
// Creating all the necessary instances of snake game
public Controller() throws InterruptedException {
food = new Food();
grid_pane = new GridPane();
//assigning a random food position to the food apple
assign_random_position_to_food();
snake = new Snake(food);
board = new Board();
move = new Movement(snake);
board.generateBoard(food.row, food.col, snake);
Parent root = grid_pane;
scene = new Scene(root, Board.BOARDHEIGHT,Board.BOARDWIDTH);
}
public void run_game() throws InterruptedException {
snake = move.move_RIGHT();
scene.setRoot( grid_pane);
}
public void assign_board_to_grid(){
for ( int row = 0; row < board.board.length; ++row)
for( int col = 0; col < board.board[row].length; ++col )
grid_pane.add(board.board[row][col], row, col, 1, 1);
}
public void assign_random_position_to_food(){
food.RandomPosition();
}
}
Board.java
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class Board {
public static int BOARDHEIGHT = 500;
public static int BOARDWIDTH = 500;
public static int BLOCKHEIGHT = 20;
public static int BLOCKWIDTH = 20;
public static int TOTAL_BLOCKS_ROW = BOARDHEIGHT/ BLOCKHEIGHT;
public static int TOTAL_BLOCKS_COL = BOARDWIDTH/ BLOCKWIDTH;
public ImageView[][] board;
public Image black_square;
public Image apple;
public Image snake_dot;
public GridPane gridPane = new GridPane();
public void assign_images(){
try{
apple = new Image("images/apple.png");
snake_dot = new Image("images/dot.png");
black_square = new Image("images/black_square.png");
}catch(Exception e){
System.out.println("Error: related to the address of images");
}
}
public Board(){
assign_images();
//initializing the board
board = new ImageView[TOTAL_BLOCKS_ROW][TOTAL_BLOCKS_COL];
}
public void generateBoard(int food_x, int food_y, Snake snake_body) {
for(int row=0; row< TOTAL_BLOCKS_ROW; row++){
for(int col=0; col< TOTAL_BLOCKS_COL; col++){
if(row == food_x && col == food_y)// && check if it is not on snake body)
board[row][col] = new ImageView(apple);
else if( snake_body.is_snake_present(row,col) && col != 0)
board[row][col] = new ImageView(snake_dot);
else
board[row][col] = new ImageView(black_square);
// Setting the size of each block on the scene
board[row][col].setFitHeight(BLOCKHEIGHT);
board[row][col].setFitWidth(BLOCKWIDTH);
Controller.grid_pane.add(board[row][col], row, col, 1 ,1);
}
}
}
}
Movement.java
public class Movement {
public Snake snake;
public static int new_y_position;
public static int new_x_position;
public Movement(Snake snake){
this.snake = snake;
}
public Snake move_RIGHT(){
new_x_position = snake.getHead_x() + 1;
new_y_position = snake.getHead_y();
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//System.out.println(new_x_position);
snake.setHead_x(new_x_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setX(b.getX() + 1);
snake.snake.set(i,b);
}
// System.out.println(snake);
return snake;
}
public Snake move_LEFT(){
new_x_position = snake.getHead_x() - 1;
new_y_position = snake.getHead_y();
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_x(new_x_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setX(b.getX() - 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public Snake move_UP(){
new_x_position = snake.getHead_x();
new_y_position = snake.getHead_y() + 1;
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_y(new_y_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setY(b.getY() + 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public Snake move_DOWN(){
new_x_position = snake.getHead_x();
new_y_position = snake.getHead_y() - 1;
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_y(new_y_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setY(b.getY() - 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public boolean check_if_snake_is_in_bounds(int x, int y){
return x >= 0 && x <= Board.TOTAL_BLOCKS_COL && y >= 0 && y <= Board.TOTAL_BLOCKS_ROW;
}
}
Snake.java
import java.util.ArrayList;
public class Snake {
public ArrayList<Block> snake = new ArrayList<>();
public int snake_size = snake.size();
int head_x, head_y;
public Snake(Food food){
// initializes a snake head location on board and stores it in a list.
do{
head_x = (int) (Math.random()*Board.TOTAL_BLOCKS_COL);
head_y = (int) (Math.random()*Board.TOTAL_BLOCKS_ROW);
}while(food.getRow() == head_x || food.getCol() == head_y);
//inserting head and a block in snake arraylist
snake.add(new Block(head_x, head_y));
snake.add(new Block(head_x - 1, head_y));
}
// Adds new body part when snake eats an apple.
public void add_snake_body() {
snake.add( retrieve_new_block_position() );
}
// gets new snake body part position.
public Block retrieve_new_block_position(){
int last_block_x = snake.get(snake_size - 1).getX();
int last_block_y = snake.get(snake_size - 1).getY();
int second_last_block_x = snake.get(snake_size - 2).getX();
int second_last_block_y = snake.get(snake_size - 2).getY();
int new_block_x;
int new_block_y;
if(second_last_block_x == last_block_x){
new_block_x = last_block_x;
new_block_y = last_block_y - 1;
}
else{
new_block_x = last_block_x - 1;
new_block_y = last_block_y;
}
return new Block(new_block_x, new_block_y);
}
//checks if a position is occupied by a snake body part.
public boolean is_snake_present(int row, int col){
int index = 0;
int snake_curr_block_x;
int snake_curr_block_y;
while(index < snake.size()){
snake_curr_block_x = snake.get(index).getX();
snake_curr_block_y = snake.get(index).getY();
if( snake_curr_block_x == row && snake_curr_block_y == col)
return true;
index++;
}
return false;
}
//GETTER & SETTER METHODS
public ArrayList<Block> getSnake() {
return snake;
}
public int getHead_x() {
return head_x;
}
public void setHead_x(int head_x) {
this.head_x = head_x;
}
public int getHead_y() {
return head_y;
}
public void setHead_y(int head_y) {
this.head_y = head_y;
}
}
Food.java
import java.util.Random;
public class Food {
int row;
int col;
public Food(){
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public void RandomPosition(){
this.row = (int) (Math.random() * Board.TOTAL_BLOCKS_ROW);
this.col = (int) (Math.random() * Board.TOTAL_BLOCKS_COL);
System.out.println(this.row+" -food- "+ this.col);
//need to check if it clashes with the snake body................
}
}
Block.java
public class Block {
private int x;
private int y;
public Block(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
I have the following code:
package myprojectgame.entities.creature;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import myprojectgame.Game;
import myprojectgame.Handler;
import myprojectgame.gfx.Animation;
import myprojectgame.gfx.Assets;
import myprojectgame.input.KeyManager;
import static myprojectgame.input.KeyManager.keys;
public abstract class Player extends Creature {
// Animations ---> while moving
private Animation down;
private Animation up;
private Animation left;
private Animation right;
// Animations --> idle
private Animation down_idle;
private Animation up_idle;
private Animation left_idle;
private Animation right_idle;
// Last pressed boolean variable --> initialize it to down
public boolean lastPressed = handler.getKeyManager().down;
public Player(Handler handler,float x, float y) {
super(handler,x, y,Creature.DEFAULT_CREATURE_WIDTH,Creature.DEFAULT_CREATURE_HEIGHT);
bounds.x = 16;
bounds.y = 14;
bounds.width = 25;
bounds.height = 43;
// Animations --> while moving instantiation
down = new Animation(300,Assets.player_down);
left = new Animation(300,Assets.player_left);
right = new Animation(300,Assets.player_right);
up = new Animation(300,Assets.player_up);
// Animations --> while idle instantiation
down_idle= new Animation(500,Assets.player_down_idle);
right_idle= new Animation(500,Assets.player_right_idle);
left_idle= new Animation(500,Assets.player_left_idle);
up_idle= new Animation(500,Assets.player_up_idle);
}
#Override
public void tick() {
down.tick();
up.tick();
right.tick();
left.tick();
down_idle.tick();
up_idle.tick();
right_idle.tick();
left_idle.tick();
getInput();
move();
handler.getCamera().centerOnEntity(this);
}
private void getInput() {
xMove = 0;
yMove = 0;
if (handler.getKeyManager().up) {
yMove = -speed;
lastPressed = handler.getKeyManager().up;
}
if (handler.getKeyManager().down) {
yMove = speed;
lastPressed = handler.getKeyManager().down;
}
if (handler.getKeyManager().left) {
xMove = -speed;
lastPressed = handler.getKeyManager().left;
}
if (handler.getKeyManager().right) {
xMove = speed;
lastPressed = handler.getKeyManager().right;
}
}
#Override
public void render(Graphics g) {
g.drawImage(getCurrentAnimationFrame(),(int) (x - handler.getCamera().getxOffset()), (int) (y - handler.getCamera().getyOffset()),(width),(height), null);
}
private BufferedImage getCurrentAnimationFrame() {
if (handler.getKeyManager().left && lastPressed == handler.getKeyManager().left) {
return left.getCurrentFrame();
} else if ( !(handler.getKeyManager().left)) {
return left_idle.getCurrentFrame();
}
if (handler.getKeyManager().right && lastPressed == handler.getKeyManager().right) {
return right.getCurrentFrame();
} else if ( !(handler.getKeyManager().right) && lastPressed == handler.getKeyManager().right) {
return right_idle.getCurrentFrame();
}
if (handler.getKeyManager().up && lastPressed == handler.getKeyManager().up) {
return up.getCurrentFrame();
} else if ( !(handler.getKeyManager().up) && lastPressed == handler.getKeyManager().up ) {
return up_idle.getCurrentFrame();
}
if (handler.getKeyManager().down && lastPressed == handler.getKeyManager().down) {
return down.getCurrentFrame();
} else if ( !(handler.getKeyManager().down) && lastPressed ==
handler.getKeyManager().down ) {
return down_idle.getCurrentFrame();
}
return null;
}
}
The problem is that I cannot get my getCurrentAnimationFrame() method to return the proper idle animations(or in this iteration of my code,any other animation besides left and left_idle).
My keys are defined in my KeyManager class like this:
up = keys[KeyEvent.VK_W] || keys[KeyEvent.VK_UP];
down = keys[KeyEvent.VK_S] || keys[KeyEvent.VK_DOWN];
left = keys[KeyEvent.VK_A] || keys[KeyEvent.VK_LEFT];
right = keys[KeyEvent.VK_D] || keys[KeyEvent.VK_RIGHT];
How can I properly implement Key events/strokes to return the right animations on key release/key press?
Your conditions and boolean logic are overcomplicated:
private void getInput() {
xMove = 0;
yMove = 0;
if (handler.getKeyManager().up) {
yMove = -speed;
lastPressed = handler.getKeyManager().up;
}
//...
}
private BufferedImage getCurrentAnimationFrame() {
if (handler.getKeyManager().left && lastPressed == handler.getKeyManager().left) {
return left.getCurrentFrame();
} else if ( !(handler.getKeyManager().left)) {
return left_idle.getCurrentFrame();
}
//...
return null;
}
Is same as:
private void getInput() {
xMove = 0;
yMove = 0;
KeyManager km = handler.getKeyManager();
if (km.up) {
yMove = -speed;
lastPressed = true;
}
//...
}
private BufferedImage getCurrentAnimationFrame() {
KeyManager km = handler.getKeyManager();
if (km.left && lastPressed) {
// replaced lastPressed == handler.getKeyManager().left since km.left must be true
return left.getCurrentFrame();
} else if (!km.left) {
return left_idle.getCurrentFrame();
}
//...
return null;
}
I do not see where are you setting lastPressed to false, looks to me it will be set to true (with first key press) and remains true. Since it is always true, your condition in getCurrentAnimationFrame is effectively:
private BufferedImage getCurrentAnimationFrame() {
KeyManager km = handler.getKeyManager();
if (km.left) {
return left.getCurrentFrame();
} else {
return left_idle.getCurrentFrame();
}
//UNREACHABLE CODE!
return null;
}
Even if it doesn't remain true, your code is like if left, return left animation, if not left return left idle animation. I think your somehow mixed booleans with key codes as you say "lastPressed variable is supposed to store the value of the last pressed key".
I would probably define direction enum:
public enum DirectionEnum {
LEFT, RIGHT, UP, DOWN;
}
And use it like this:
DirectionEnum lastPressed = null;
private void getInput() {
xMove = 0;
yMove = 0;
KeyManager km = handler.getKeyManager();
if (km.up) {
yMove = -speed;
lastPressed = DirectionEnum.UP;
}
//...
}
private BufferedImage getCurrentAnimationFrame() {
KeyManager km = handler.getKeyManager();
if (lastPressed == null) {
if (km.left) {
return left.getCurrentFrame();
}
//...
} else {
switch (lastPressed) {
case DOWN:
if (!km.down){
return down_idle.getCurrentFrame();
}
break;
//...
default:
throw new RuntimeException("Invalid direction " + lastPressed);
}
}
return null;
}
But I do not know if it is correct, because lastPressed will be null only first time (or never), and then you will see only idle animations. So you should probably decide when to set lastPressed back to null?
This question already has answers here:
How to change JFrame icon [duplicate]
(8 answers)
Closed 6 years ago.
How do I add an icon to this snake game and where do I put it, also how do I increase speed of the game after so many points? The code below is the class in which I believe these two pieces of code should go.
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class SnakeGame extends JFrame {
private static final long FRAME_TIME = 1000L / 50L;
private static final int MIN_SNAKE_LENGTH = 5;
private static final int MAX_DIRECTIONS = 3;
private BoardPanel board;
private SidePanel side;
private Random random;
private Clock logicTimer;
private boolean isNewGame;
private boolean isGameOver;
private boolean isPaused;
private LinkedList<Point> snake;
private LinkedList<Direction> directions;
private int score;
private int foodsEaten;
private int nextFoodScore;
private SnakeGame() {
super("Snake");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
this.board = new BoardPanel(this);
this.side = new SidePanel(this);
add(board, BorderLayout.CENTER);
add(side, BorderLayout.EAST);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.South && last != Direction.North) {
directions.addLast(Direction.North);
}
}
}
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.North && last != Direction.South) {
directions.addLast(Direction.South);
}
}
}
break;
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.East && last != Direction.West) {
directions.addLast(Direction.West);
}
}
}
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.West && last != Direction.East) {
directions.addLast(Direction.East);
}
}
}
break;
case KeyEvent.VK_P:
if(!isGameOver) {
isPaused = !isPaused;
logicTimer.setPaused(isPaused);
}
break;
case KeyEvent.VK_ENTER:
if(isNewGame || isGameOver) {
resetGame();
}
break;
}
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void startGame() {
this.random = new Random();
this.snake = new LinkedList<>();
this.directions = new LinkedList<>();
this.logicTimer = new Clock(10.0f);
//////////////////////////////////////////////////////////////////////////////////////////////////
this.isNewGame = true;
logicTimer.setPaused(true);
while(true) {
long start = System.nanoTime();
logicTimer.update();
if(logicTimer.hasElapsedCycle()) {
updateGame();
}
board.repaint();
side.repaint();
long delta = (System.nanoTime() - start) / 1000000L;
if(delta < FRAME_TIME) {
try {
Thread.sleep(FRAME_TIME - delta);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
private void updateGame() {
TileType collision = updateSnake();
if(collision == TileType.Food) {
foodsEaten++;
score += nextFoodScore;
spawnFood();
} else if(collision == TileType.SnakeBody) {
isGameOver = true;
logicTimer.setPaused(true);
} else if(nextFoodScore > 10) {
}
}
private TileType updateSnake() {
Direction direction = directions.peekFirst();
Point head = new Point(snake.peekFirst());
switch(direction) {
case North:
head.y--;
break;
case South:
head.y++;
break;
case West:
head.x--;
break;
case East:
head.x++;
break;
}
if(head.x < 0 || head.x >= BoardPanel.COL_COUNT || head.y < 0 || head.y >= BoardPanel.ROW_COUNT) {
return TileType.SnakeBody;
}
TileType old = board.getTile(head.x, head.y);
if(old != TileType.Food && snake.size() > MIN_SNAKE_LENGTH) {
Point tail = snake.removeLast();
board.setTile(tail, null);
old = board.getTile(head.x, head.y);
}
if(old != TileType.SnakeBody) {
board.setTile(snake.peekFirst(), TileType.SnakeBody);
snake.push(head);
board.setTile(head, TileType.SnakeHead);
if(directions.size() > 1) {
directions.poll();
}
}
return old;
}
private void resetGame() {
this.score = 0;
this.foodsEaten = 0;
this.isNewGame = false;
this.isGameOver = false;
Point head = new Point(BoardPanel.COL_COUNT / 2, BoardPanel.ROW_COUNT / 2);
snake.clear();
snake.add(head);
board.clearBoard();
board.setTile(head, TileType.SnakeHead);
directions.clear();
directions.add(Direction.North);
logicTimer.reset();
spawnFood();
}
public boolean isNewGame() {
return isNewGame;
}
public boolean isGameOver() {
return isGameOver;
}
public boolean isPaused() {
return isPaused;
}
private void spawnFood() {
this.nextFoodScore = 10;
int index = random.nextInt(BoardPanel.COL_COUNT * BoardPanel.ROW_COUNT - snake.size());
int freeFound = -1;
for(int x = 0; x < BoardPanel.COL_COUNT; x++) {
for(int y = 0; y < BoardPanel.ROW_COUNT; y++) {
TileType type = board.getTile(x, y);
if(type == null || type == TileType.Food) {
if(++freeFound == index) {
board.setTile(x, y, TileType.Food);
break;
}
}
}
}
}
public int getScore() {
return score;
}
public int getFoodsEaten() {
return foodsEaten;
}
public int getNextFoodScore() {
return nextFoodScore;
}
public Direction getDirection() {
return directions.peek();
}
public static void main(String[] args) {
SnakeGame snake = new SnakeGame();
snake.startGame();
}
}
Create a new ImageIcon object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame with setIconImage():
myFrame.setIconImage(img.getImage());
Also checkout setIconImages() which takes a List instead.
How to change JFrame icon
It 's not my answer !!!!
I'm working on creating a simple mine sweeper game in java using JButtons. So far I have a code that creates a 20x20 grid of JButtons, but I am unsure of how I can get my bombs randomly assigned to multimple JButtons durring the game.
Here is what I have written so far:
MineSweeper Class:
import javax.swing.*;
import java.awt.GridLayout;
public class MineSweeper extends JFrame {
JPanel p = new JPanel();
bombButton points[][]= new bombButton[20][20];
public static void main(String args[]){
new MineSweeper();
}
public MineSweeper(){
super("Mine Sweeper Version: Beta");
setSize(400,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(20,20));
int y=0;
int counter=0;
while(counter<20){
for(int x=0;x<20;x++){
points[x][y] = new bombButton();
p.add(points[x][y]);
}
y++;
counter++;
}
add(p);
setVisible(true);
}
}
bombButton Class:
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URL;
public class bombButton extends JButton implements ActionListener {
ImageIcon Bomb,zero,one,two,three,four,five,six,seven,eight;
public bombButton(){
URL imageBomb = getClass().getResource("Bomb.png");
Bomb= new ImageIcon(imageBomb);
URL imageZero = getClass().getResource("0.jpg");
zero= new ImageIcon(imageZero);
URL imageOne = getClass().getResource("1.jpg");
one= new ImageIcon(imageOne);
URL imageTwo = getClass().getResource("2.jpg");
two= new ImageIcon(imageTwo);
URL imageThree = getClass().getResource("3.jpg");
three= new ImageIcon(imageThree);
URL imageFour = getClass().getResource("4.jpg");
four= new ImageIcon(imageFour);
URL imageFive = getClass().getResource("5.jpg");
five= new ImageIcon(imageFive);
URL imageSix = getClass().getResource("6.jpg");
six= new ImageIcon(imageSix);
URL imageSeven = getClass().getResource("7.jpg");
seven= new ImageIcon(imageSeven);
URL imageEight = getClass().getResource("8.jpg");
eight= new ImageIcon(imageEight);
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
switch(){
case 0:
setIcon(null);
break;
case 1:
setIcon(Bomb);
break;
case 2:
setIcon(one);
break;
case 3:
setIcon(two);
break;
case 4:
setIcon(three);
break;
case 5:
setIcon(four);
break;
case 6:
setIcon(five);
break;
case 7:
setIcon(six);
break;
case 8:
setIcon(seven);
break;
case 9:
setIcon(eight);
break;
}
}
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
}
As you can see I already have a randomizer set up, I just don't know how I should implement it. Should I use (X,Y) cordinates? How do I assign my bombs to random JButtons?
Thnak you to all in advance!
Create an ArrayList<JButton>, fill it with all your buttons, call Collections.shuffle(..) on the list, and then select the first N buttons to add mines to.
Having said this, my real recommendation is to chuck all this and go the MVC route where your data model, including where the mines are located, and your GUI are completely distinct.
here are some of my prior musings on this problem from 2011.
here are my Miseweeper Clone
package MWeeper;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class MMWeeper extends JFrame implements Runnable {
private JFrame mainFrame ;
private JPanel mainPanel;
private int boardX = 15;
private int boardY = 15;
private int bombs = 35;
private int bombsMarked;
private int cleanFields;
private int seconds;
private boolean gameOver = false;
private Map<Integer, Map<Integer, mweeperField>> boardMap;
private Map<Integer,position> bombMap;
private JPanel boardPanel;
private JPanel headPanel;
private JTextField bombsField;
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainFrame = new JFrame("MMWEEEEEEPER");
int w = Toolkit.getDefaultToolkit().getScreenSize().width;
int h = Toolkit.getDefaultToolkit().getScreenSize().height;
mainFrame.setPreferredSize(new Dimension(350,390));
mainFrame.setResizable(true);
mainPanel = new JPanel(new BorderLayout());
init();
//setContent();
setPanel();
mainFrame.add(mainPanel);
mainFrame.setContentPane(mainFrame.getContentPane());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
});
}
private void init() {
bombMap = new HashMap<Integer, MMWeeper.position>();
boardMap = new HashMap<Integer, Map<Integer,mweeperField>>();
bombsMarked = 0;
cleanFields = (boardX * boardY) - bombs;
seconds = 0;
for(int i = 1; i<= boardX; i++) {
boardMap.put(i, new HashMap<Integer, mweeperField>());
for(int j = 1; j <= boardY; j++) {
boardMap.get(i).put(j, new mweeperField(i, j ));
}
}
placeBombs();
}
private boolean placeBombs() {
Random pX = new Random();
Random pY = new Random();
int bombCount = 0;
//while( bombMap.size() < bombs ) {
while(bombCount < bombs) {
int x = (1 + pX.nextInt( boardX ) );
int y = (1 + pY.nextInt( boardY ) );
if(!boardMap.get(x).get(y).isBomb() ) {
boardMap.get(x).get(y).setBomb();
bombCount++;
bombMap.put(bombCount, new position(x, y));
}
}
return true;
}
private void setPanel() {
mainPanel.add(head(), BorderLayout.PAGE_START);
mainPanel.add(board(), BorderLayout.CENTER);
}
private JPanel head() {
headPanel = new JPanel(new BorderLayout());
bombsField = new JTextField(6);
bombsField.setEditable(true);
bombsField.setText( String.valueOf(bombs));
JButton start = new JButton("Start");
start.addActionListener( new mweeperAction(GameActions.START) );
headPanel.add(bombsField, BorderLayout.LINE_START);
headPanel.add(start, BorderLayout.LINE_END);
return headPanel;
}
private JPanel board() {
boardPanel = new JPanel();
GridLayout gLayout = new GridLayout(15, 15, 0, 0 );
boardPanel.setLayout(gLayout);
for( Integer x : boardMap.keySet()) {
for(Integer y : boardMap.get(x).keySet()) {
boardPanel.add( boardMap.get(x).get(y).getButton() );
}
}
return boardPanel;
}
private void gameOver() {
this.gameOver = true;
for( Integer x : boardMap.keySet()) {
for(Integer y : boardMap.get(x).keySet()) {
boardMap.get(x).get(y).trigger();
}
}
}
public class mweeperField implements mousePerformer {
private position pos;
private FieldStatus status = FieldStatus.HIDE_UNMARKED;
private boolean isBomb = false;
private int bombsAroundMe = 0;
private JButton but;
private boolean isTriggered = false;
public mweeperField( int x, int y ) {
this.pos = new position(x, y);
init();
}
public mweeperField( position p ) {
this.pos = p;
init();
}
public void resetField() {
status = FieldStatus.HIDE_UNMARKED;
isBomb = false;
bombsAroundMe = 0;
isTriggered = false;
but.setFont(new Font("Arial", Font.BOLD, 13));
but.setBackground(Color.LIGHT_GRAY);
but.setText(" ");
but.setEnabled(true);
}
public void setBomb() {
this.isBomb = true;
}
public boolean isBomb() {
return isBomb;
}
private void init() {
but = new JButton(" ");
but.setMaximumSize(new Dimension(16, 16));
but.setMinimumSize(new Dimension(16, 16));
but.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
but.setMargin(new Insets(0, 0, 0, 0));
but.setBackground(Color.LIGHT_GRAY);
but.addMouseListener(new mweeperMouseListener(this.pos, this));
but.setFont(new Font("Arial", Font.BOLD, 14));
}
private void setButton() {
switch(status) {
case HIDE_MARKED:
//but.setForeground( new Color(224, 124, 168) );
but.setForeground( Color.RED);
but.setText("#");
but.setEnabled(true);
break;
case HIDE_UNMARKED:
but.setForeground(Color.BLACK);
but.setText(" ");
but.setEnabled(true);
break;
case OPEN_NOBOMB:
switch(this.bombsAroundMe) {
case 1:
case 2:
but.setForeground(Color.BLUE);
break;
case 3:
case 4:
but.setForeground(Color.MAGENTA);
break;
case 5:
case 6:
but.setForeground(Color.RED);
break;
case 7:
case 8:
but.setForeground(Color.PINK);
break;
}
String butText = " ";
if(this.bombsAroundMe > 0) {
butText = String.valueOf(this.bombsAroundMe);
}
but.setEnabled(false);
but.setText( butText );
break;
case OPEN_BOMB: // GAME OVER
but.setForeground(Color.BLACK);
but.setFont(new Font("Arial", Font.BOLD, 20));
but.setVerticalAlignment(SwingConstants.CENTER);
but.setHorizontalAlignment(SwingConstants.CENTER);
but.setText("*");
break;
}
// but.setEnabled(false);
but.validate();
but.repaint();
boardPanel.validate();
boardPanel.repaint();
mainPanel.repaint();
}
public JButton getButton() {
return but;
}
/*
+-----+-----+-----+
| x-1 | x | x+1 |
| y-1 | y-1 | y-1 |
+-----+-----+-----+
| x-1 | x/y | x+1 |
| y | | y |
+-----+-----+-----+
| x-1 | x | x+1 |
| y+1 | y+1 | y+1 |
+-----+-----+-----+
*/
private void scan() {
bombsAroundMe = 0;
for(Integer k : pos.posAroundMe.keySet() ) {
position p2 = pos.posAroundMe.get(k);
if(boardMap.get(p2.x).get(p2.y).isBomb()) {
bombsAroundMe++;
}
}
}
public void trigger() {
if(!isTriggered) {
isTriggered = true;
if(!isBomb) {
status = FieldStatus.OPEN_NOBOMB;
}else {
status = FieldStatus.OPEN_BOMB;
}
scan();
setButton();
if(bombsAroundMe == 0) {
// um mich herum triggern
for(Integer k : pos.posAroundMe.keySet() ) {
position p2 = pos.posAroundMe.get(k);
boardMap.get(p2.x).get(p2.y).trigger();
}
}
}
}
#Override
public void doClick(MouseEvent e, position pos) {
switch(e.getButton()) {
case 1: //Links Klick = triggern wenn nich markiert und hide
if(this.status.equals(FieldStatus.HIDE_UNMARKED)){
if(this.isBomb) {
// GAME OVER =8-(
status = FieldStatus.OPEN_BOMB;
but.setBackground(Color.RED);
gameOver();
}else {
trigger();
}
}
break;
case 3: // Rechtsklick
if(this.status.equals(FieldStatus.HIDE_UNMARKED)) {
// Mark Field
this.status = FieldStatus.HIDE_MARKED;
bombsMarked++;
}else {
// Umark Field
this.status = FieldStatus.HIDE_UNMARKED;
bombsMarked--;
}
setButton();
break;
}
}
}
public class position {
public int x = 0;
public int y = 0;
public Map<Integer, position> posAroundMe;
public position(int x, int y) {
this.x = x;
this.y = y;
posAroundMe = new HashMap<Integer, MMWeeper.position>();
setPosAroundMe();
}
public position(int x, int y, boolean setPos) {
posAroundMe = new HashMap<Integer, MMWeeper.position>();
this.x = x;
this.y = y;
}
private void setPosAroundMe() {
int c = 1;
for(int x2 = (x-1); x2 <= (x+1); x2++) {
for(int y2 = (y-1); y2 <= (y+1); y2++) {
if( ((x2 != x) || (y2 != y)) && ( x2>0 && x2<=boardX && y2>0 && y2<=boardY ) ){
posAroundMe.put(c++, new position(x2, y2, false));
}
}
}
}
}
public enum FieldStatus{
HIDE_UNMARKED,
HIDE_MARKED,
OPEN_NOBOMB,
OPEN_BOMB;
}
public enum GameActions{
START;
}
public class mweeperAction extends AbstractAction{
private GameActions gameAction;
public mweeperAction(GameActions ga ) {
this.gameAction = ga;
}
#Override
public void actionPerformed(ActionEvent ae) {
switch(gameAction) {
case START:
for( Integer x : boardMap.keySet()) {
for(Integer y : boardMap.get(x).keySet()) {
boardMap.get(x).get(y).resetField();;
boardMap.get(x).get(y).getButton().validate();
boardMap.get(x).get(y).getButton().repaint();;
}
}
int newBombCount = Integer.valueOf(bombsField.getText()) ;
if(newBombCount < 10) {
newBombCount = 10;
}
if(newBombCount > ((boardX * 2) + 20 ) ){
newBombCount = ((boardX * 2) + 20 );
}
bombs = newBombCount;
bombsField.setText(String.valueOf(bombs) );
placeBombs();
boardPanel.validate();
boardPanel.repaint();
mainPanel.repaint();
break;
}
}
}
public class mweeperMouseListener implements MouseListener{
private position pos;
mousePerformer performer;
public mweeperMouseListener(position pos, mousePerformer acPerf) {
this.pos = pos;
this.performer = acPerf;
}
#Override
public void mouseClicked(MouseEvent e) {
this.performer.doClick(e , pos );
}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
}
public interface mousePerformer{
public void doClick(MouseEvent e, position pos );
}
public interface actionPerformer{
public void doAction(ActionEvent ae, GameActions ga );
}
}