Minesweeper draw number of nearby mines - java

I need to do a Minesweeper game. I have most of the methods down, but I cannot figure out a way to draw the number of mines around a given tile. I have a method that returns the number of mines around that tile, but no such method to actually display that number inside the tile in the game.
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.net.URL;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
private static final long serialVersionUID = 3426940946811133635L;
private static final int GRID_X = 25;
private static final int GRID_Y = 25;
private static final int INNER_CELL_SIZE = 29;
private static final int TOTAL_COLUMNS = 9;
private static final int TOTAL_ROWS = 10; //Last row has only one cell
public int x = -1;
public int y = -1;
public int mouseDownGridX = 0;
public int mouseDownGridY = 0;
private ImageIcon icon;
private static char minefield[][];
public Color[][] colorArray = new Color[TOTAL_COLUMNS][TOTAL_ROWS];
public MyPanel() { //This is the constructor... this code runs first to initialize
if (INNER_CELL_SIZE + (new Random()).nextInt(1) < 1) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("INNER_CELL_SIZE must be positive!");
}
if (TOTAL_COLUMNS + (new Random()).nextInt(1) < 2) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_COLUMNS must be at least 2!");
}
if (TOTAL_ROWS + (new Random()).nextInt(1) < 3) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_ROWS must be at least 3!");
}
for (int x = 0; x < TOTAL_COLUMNS; x++) { //Top row
colorArray[x][0] = Color.LIGHT_GRAY;
}
for (int y = 0; y < TOTAL_ROWS; y++) { //Left column
colorArray[0][y] = Color.LIGHT_GRAY;
}
for (int x = 1; x < TOTAL_COLUMNS; x++) { //The rest of the grid
for (int y = 1; y < TOTAL_ROWS; y++) {
colorArray[x][y] = Color.LIGHT_GRAY;
}
}
minefield = new char [TOTAL_COLUMNS][TOTAL_ROWS];
}
Random rando = new Random();
public static int mines = 10;
public int flags = 10;
public static int flagged = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Compute interior coordinates
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
int x2 = getWidth() - myInsets.right - 1;
int y2 = getHeight() - myInsets.bottom - 1;
int width = x2 - x1;
int height = y2 - y1;
//Paint the background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x1, y1, width + 1, height + 1);
//Draw the grid minus the bottom row (which has only one cell)
//By default, the grid will be 10x10 (see above: TOTAL_COLUMNS and TOTAL_ROWS)
g.setColor(Color.BLACK);
for (int y = 0; y <= TOTAL_ROWS - 1; y++) {
g.drawLine(x1 + GRID_X, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)), x1 + GRID_X + ((INNER_CELL_SIZE + 1) * TOTAL_COLUMNS), y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)));
}
for (int x = 0; x <= TOTAL_COLUMNS; x++) {
g.drawLine(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y, x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y + ((INNER_CELL_SIZE + 1) * (TOTAL_ROWS - 1)));
}
//Paint cell colors
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if ((x == 0) || (y != TOTAL_ROWS - 1)) {
Color c = colorArray[x][y];
g.setColor(c);
g.fillRect(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)) + 1, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)) + 1, INNER_CELL_SIZE, INNER_CELL_SIZE);
}
}
}
}
// Places the mines in the field
public void placeMines() {
int minesPlaced = 1;
while (minesPlaced <= mines) {
int x = rando.nextInt(TOTAL_COLUMNS);
int y = rando.nextInt(TOTAL_ROWS-1);
if (minefield[x][y] != '*') {
minefield[x][y] = '*';
minesPlaced++;
}
}
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
bombCheck(i, j);
if (bombCheck(i, j) == 1) {
System.out.println(i + "," + j); // for debugging purposes
}
}
}repaint();
}
//checks a tile, white if there were no mines
public void check (int x, int y) {
colorArray[x][y] = Color.WHITE ;
repaint();
}
// Checks whether this place in the field has a bomb (1) or not (0).
public int bombCheck(int x, int y) {
if (!(x == -1 || y == -1)) {
if (minefield[x][y] == '*') {
return 1;
}
else {
minefield[x][y] = 'c';
return 0;
}
}
else{
return 0;
}
}
// Checks for mines on the 8 other tiles around the target location and returns the number of mines there are.
public int minesAround(int x, int y) {
int mines = 0;
mines += bombCheck(x-1, y-1);
mines += bombCheck(x-1, y);
mines += bombCheck(x-1, y+1);
mines += bombCheck(x, y-1);
mines += bombCheck(x, y+1);
mines += bombCheck(x+1, y-1);
mines += bombCheck(x+1, y);
mines += bombCheck(x+1, y+1);
if (mines > 0) {
return mines;
}
else{
return 0;
}
}
//What I've come up with so far for drawing the number in the tile. Does not work.
public void draw (Graphics g, int n, int x, int y) {
super.paintComponent(g);
g.drawString("" + n + "", x, y);
}
//Recursive method
public void checkAround(int x, int y) {
int minx, miny, maxx, maxy;
check(x,y);
minx = (x <= 0 ? 0 : x - 1);
miny = (y <= 0 ? 0 : y - 1);
maxx = (x >= TOTAL_COLUMNS - 1 ? TOTAL_COLUMNS - 1 : x + 1);
maxy = (y >= TOTAL_ROWS - 2 ? TOTAL_ROWS - 2 : y + 1);
for (int i = minx; i < maxx; i ++) {
for (int j = miny; j <= maxy; j ++) {
if (bombCheck(i,j) == 0 && colorArray[i][j] != Color.WHITE) {
check(i,j);
if (minesAround(i,j) == 0) {
checkAround(i,j);
}
if (minesAround(i,j) == 1) {
draw(getGraphics(),1,i,j); // Does not work.
repaint();
}
}
}
}
}
//Flag
public int checkflag(int x, int y){
int status = 0;
if (!(x == -1 || y == -1)) {
if (colorArray[x][y] == Color.RED) {
status += 1;
}else {
status += 0;
}
}
return status;
}
//Resets field
public void reset() {
for (int i = 0; i < TOTAL_COLUMNS; i++) {
for (int j = 0 ;j < TOTAL_ROWS; j++) {
colorArray[i][j] = Color.LIGHT_GRAY;
minefield[i][j] = ' ';
MyMouseAdapter.f = 1;
repaint();
}
}
placeMines();
}
public int getGridX(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return x;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return x;
}
public int getGridY(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return y;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return y;
}
public ImageIcon getIcon() {
return icon;
}
public void setIcon(ImageIcon icon) {
this.icon = icon;
}
}
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Random;
import javax.swing.JFrame;
public class MyMouseAdapter extends MouseAdapter {
public static int f = 1;
public void mousePressed(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame) c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0);
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
myPanel.mouseDownGridX = myPanel.getGridX(x, y);
myPanel.mouseDownGridY = myPanel.getGridY(x, y);
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
myPanel1.mouseDownGridX = myPanel1.getGridX(x3, y3);
myPanel1.mouseDownGridY = myPanel1.getGridY(x3, y3);
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
public void mouseReleased(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame)c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
int gridX = myPanel.getGridX(x, y);
int gridY = myPanel.getGridY(x, y);
if ((myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX == -1) || (gridY == -1)) {
//Do nothing
}else if (gridX == 0 && gridY == 9) {
myPanel.reset();
} else {
if ((myPanel.mouseDownGridX != gridX) || (myPanel.mouseDownGridY != gridY)) {
//Released the mouse button on a different cell where it was pressed
//Do nothing
} else {
//Released the mouse button on the same cell where it was pressed
if (!(myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
if (!(myPanel.colorArray[gridX][gridY] == Color.RED)) {
if (myPanel.bombCheck(gridX, gridY) == 0) {
myPanel.checkAround(gridX, gridY);
}
else{
myPanel.colorArray[gridX][gridY] = Color.BLACK ;
System.out.println("You've Lost!");
myPanel.reset();
myPanel.repaint();
}
}
}
}
}
}
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
int gridX1 = myPanel1.getGridX(x3, y3);
int gridY1 = myPanel1.getGridY(x3, y3);
int flags = 10;
if ((myPanel1.mouseDownGridX == -1) || (myPanel1.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX1 == -1) || (gridY1 == -1)) {
//Is releasing outside
//Do nothing
} else {
if ((myPanel1.mouseDownGridX != gridX1) || (myPanel1.mouseDownGridY != gridY1)) {
}else{
if (!(myPanel1.colorArray[gridX1][gridY1] == Color.WHITE)) {
if (myPanel1.checkflag(gridX1, gridY1) == 0) {
if (!(f > flags)) {
if (myPanel1.bombCheck(gridX1, gridY1) == 1) {
MyPanel.flagged ++;
if (MyPanel.flagged == 10) {
System.out.println("You've Won! Congratulations!");
myPanel1.reset();
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
}
}
myPanel1.colorArray[gridX1][gridY1] = Color.RED ;
myPanel1.repaint();
f ++;
}
}
else {
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
f --;
}
}
}
}
}
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
}
-
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame myFrame = new JFrame("Color Grid");
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.setLocation(400, 150);
myFrame.setSize(400, 400);
MyPanel myPanel = new MyPanel();
myFrame.add(myPanel);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
myFrame.addMouseListener(myMouseAdapter);
myFrame.setVisible(true);
myPanel.placeMines();
}
}
This is only my first year studying Computer science, but if my intuition is correct, my draw method is drawing the number behind the tiles. These are just my thoughts, I have relatively little to no experience with Java.

In your paintComponent() add something like this:
Font f = new Font("Dialog", Font.PLAIN, 12); // choose a font for the numbers
g.setFont(f);
// Draw cell numbers
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if (/* check if the (x,y) cell is uncovered */) {
int around = minesAround(x, y);
g.drawString(String.valueOf(around), /*cell x coord*/, /*cell y coord*/);
}
}
}
Alternatively, you can use an image for each cell number instead of using a string.

Related

Java swing game JPanel layout assistance

I'm in the process of making a game which has 3 sections to the JFrame, the game map, a "player view" : just an animation of the player moving and will hopefully include different enemy designs later and finally a inventory section I haven't started on yet.
What would be the best way in terms of class and method layouts to have all these 3 sections of my JPanel able to communicate with one another and dynamically change based on the current situation (having the player view show an enemy when their tile collides with another or have it not update if the player doesnt move (s)).
I don't mind re-writing the entire game just this is my first game and would like some assistance on structure.
And I'm not sure exactly how paintComponent works or repaint() method. Or how draw(Graphics g) is called
to make the graphics???
Code for context and testing:
TextGamePanel.java :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Random;
public class TextGamePanel extends JPanel implements ActionListener{
private static final int HEIGHT = 30, WIDTH = 30, MAPVISIBILITY = 8;
private static final int SCREEN_WIDTH = 1080;
private static final int SCREEN_HEIGHT = 1080;
private static final int UNIT_SIZE = 36;
private static final int DELAY = 10;
private String[][] mapBlank = new String[HEIGHT][WIDTH];
private ArrayList<Enemies> enemyList = new ArrayList<Enemies>();
private Random random = new Random();
private Players player;
private int turnCounter = 0;
Timer timer;
boolean active = false , movementMade = false;
TextGamePanel(){
this.setPreferredSize(new Dimension(1920, 1080));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame(){
newPlayer();
active = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
}
public void makeMap(){
for(int row = 0; row < mapBlank.length; row++){
for(int col = 0; col < mapBlank[row].length; col++){
mapBlank[row][col] = "";
}
}
for(Enemies enemy : enemyList){
mapBlank[enemy.getXPos()][enemy.getYPos()] = " *";
}
mapBlank[player.getXPos()][player.getYPos()] = " ^";
}
public void draw(Graphics g){
makeMap();
// These loops generate the
g.setColor(new Color(69, 69, 69));
g.fillRect(1080, 0, 840, 360);
g.setFont(new Font("Times Roman", Font.BOLD, 36));
g.setColor(new Color(74, 74, 74));
for(int x = 0; x < 20; x++){
g.drawString(randomString(50), 1020, UNIT_SIZE + x*UNIT_SIZE/2);
}
for(int i = 0; i < 2; i++){
for(int x = 0; x < 13; x++){
g.setColor(new Color(0+x*10, 0+x*10, 0+x*10));
g.setFont(new Font("Times Roman", Font.BOLD, 10+x*2));
g.drawString(randomString(200), 1020, 268 + x * 8);
}
}
//makes the map background grey
g.setColor(new Color(69, 69, 69));
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//Makes light for context of player view range
g.setColor(new Color(227, 201, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - MAPVISIBILITY/2 * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - MAPVISIBILITY/2 *UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE));
g.setColor(new Color(227, 180, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) *UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE));
g.setColor(new Color(240, 110, 67, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) *UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE));
g.setColor(new Color(255, 255, 255));
g.setFont(new Font("Times Roman", Font.BOLD, 36));
//draws the grid
for(int i = 0; i < SCREEN_HEIGHT/UNIT_SIZE; i++){
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
}
for(int i = 0; i < SCREEN_WIDTH/UNIT_SIZE; i++){
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
//draws only yourself and enemy around you given MAPVISIBILITY/2 = view range
int xIndex = -1, yIndex = -1;
for(int row = player.getXPos() - MAPVISIBILITY/2; row < player.getXPos() + 1 + MAPVISIBILITY/2; row++){
xIndex ++;
for(int col = player.getYPos() - MAPVISIBILITY/2; col < player.getYPos() + 1 + MAPVISIBILITY/2; col++){
yIndex++;
try{
g.drawString(mapBlank[row][col], row * UNIT_SIZE, (col + 1) * UNIT_SIZE);
}catch(Exception e){
}
}
}
// inventory section (yet to be made)
g.setColor(Color.blue);
g.fillRect(1080, 360, 840, 720);
}
public void movementPhase(){
turnCounter ++;
updateEnemyMovement();
if(turnCounter == 2){
turnCounter = 0;
newEnemy();
}
}
#Override
public void actionPerformed(ActionEvent e){
if(active){
}
}
public class MyKeyAdapter extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_Q: // Move diagonal left up.
if(player.getXPos() > 0 && player.getYPos() > 0){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_E: // Move diagonal right up.
if(player.getXPos() < HEIGHT - 1 && player.getYPos() > 0){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_Z: // Move diagonal left down.
if(player.getXPos() > 0 && player.getYPos() < WIDTH - 1){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_C: // Move diagonal right down.
if(player.getYPos() < WIDTH - 1 && player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_W: // Move up.
if(player.getYPos() > 0){
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_X: // Move down.
if(player.getYPos() < WIDTH - 1){
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_A: // Move left.
if(player.getXPos() > 0){
player.setXPos(player.getXPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_D: // Move right.
if(player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_S: // Dont Move.
movementMade = true;
break;
}
if(movementMade){
movementPhase();
movementMade = false;
}
repaint();
}
}
public void updateEnemyMovement(){
Iterator i = (Iterator) enemyList.iterator();
Enemies enemy = new Enemies();
while(i.hasNext()){
enemy = (Enemies) i.next();
enemy.move(player.getXPos(), player.getYPos());
if(enemy.getXPos() == player.getXPos() && enemy.getYPos() == player.getYPos()){
i.remove();
}
}
}
public void newPlayer(){
player = new Players(random.nextInt((int)SCREEN_WIDTH/UNIT_SIZE), random.nextInt((int)SCREEN_HEIGHT/UNIT_SIZE));
}
public void newEnemy(){
enemyList.add(new Enemies(random.nextInt(HEIGHT), random.nextInt(WIDTH)));
}
public String randomString(int n) {
int leftLimit = 49; //'0'
int rightLimit = 122; //'z'
int targetStringLength = n;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int)
(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();
return(generatedString);
}
}
`
Players.java :
public class Players{
private int x, y;
public Players(){
}
public Players(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
}
`
Enemies.java :
public class Enemies {
private int x, y;
public Enemies(){
}
public Enemies(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
/** Enemy Movement Method */
public void move(int playerX, int playerY){
if(getXPos() == playerX && getYPos() == playerY){ // x = playerX & y = playery
}/** Diagonal right down */
else if(getXPos() < playerX && getYPos() < playerY){ // x < playerX & y < playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() < playerY){ // x > playerX & y < playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal left down */
else if(getXPos() < playerX && getYPos() > playerY){ // x < playerX & y > playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() - 1); // y - 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() > playerY){ // x > playerX & y > playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() - 1); // y - 1
}/** Down */
else if(getXPos() < playerX && getYPos() == playerY){ // x < playerX & y = playerY
setXPos(getXPos() + 1); // x + 1
}/** Up */
else if(getXPos() > playerX && getYPos() == playerY){ // x > playerX & y = playerY
setXPos(getXPos() - 1); // x - 1
}/** Right */
else if(getXPos() == playerX && getYPos() < playerY){ // x = playerX & y < playerY
setYPos(getYPos() + 1); // y + 1
}/** Left */
else if(getXPos() == playerX && getYPos() > playerY){ // x = playerX & y > playerY
setYPos(getYPos() - 1); // y - 1
}
}
}
`
TextGameFrame.java :
import javax.swing.*;
public class TextGameFrame extends JFrame{
TextGameFrame(){
this.add(new TextGamePanel());
this.setTitle("Text Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
`
TextGameMain.java :
public class TextGameMain{
public static void main(String[] args){
new TextGameFrame();
}
}
`

Intersection of Rectangles for Java (Freeze Tag)

**Edited still not getting the right response **
I am not quite understanding how to figure out the intersection aspect of my project. So far I have determined the top, bottom, left and right but I am not sure where to go from there.
The main driver should call to check if my moving rectangles are intersecting and if the rectangle is froze the moving one intersecting with it should unfreeze it and change its color. I understand how to unfreeze it and change the color but for whatever the reason it isn't returning the value as true when they are intersecting and I know this code is wrong. Any helpful tips are appreciated.
*CLASS CODE*
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.awt.Color;
public class MovingRectangle {
Random rnd = new Random();
private int xCoord;
private int yCoord;
private int width;
private int height;
private int xVelocity;
private int yVelocity;
private Color color;
private boolean frozen;
private int canvas;
public MovingRectangle(int x, int y, int w, int h, int xv, int yv, int canvasSize) {
canvas = canvasSize;
xCoord = x;
yCoord = y;
width = w;
height = h;
xVelocity = xv;
yVelocity = yv;
frozen = false;
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public void draw() {
StdDraw.setPenColor(color);
StdDraw.filledRectangle(xCoord, yCoord, width, height);
}
public void move() {
if (frozen == false) {
xCoord = xCoord + xVelocity;
yCoord = yCoord + yVelocity;
}
else {
xCoord +=0;
yCoord +=0;
}
if (xCoord >= canvas || xCoord < 0) {
xVelocity *= -1;
this.setRandomColor();
}
if (yCoord >= canvas || yCoord < 0) {
yVelocity *= -1;
this.setRandomColor();
}
}
public void setColor(Color c) {
StdDraw.setPenColor(color);
}
public void setRandomColor() {
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public boolean containsPoint(double x, double y) {
int bottom = yCoord - height / 2;
int top = yCoord + height / 2;
int left = xCoord - width / 2;
int right = xCoord + width / 2;
if (x > left && x < right && y > bottom && y < top) {
color = StdDraw.RED;
return true;
} else {
return false;
}
}
public boolean isFrozen() {
if (frozen) {
return true;
} else {
return false;
}
}
public void setFrozen(boolean val) {
frozen = val;
}
public boolean isIntersecting(MovingRectangle r) {
int top = xCoord + height/2;
int bottom = xCoord - height/2;
int right = yCoord + width/2;
int left = yCoord - width/2;
int rTop = r.xCoord + r.height/2;
int rBottom = r.xCoord - r.height/2;
int rRight = r.yCoord + r.width/2;
int rLeft = r.yCoord - r.width/2;
if(right <= rRight && right >= rLeft || bottom <= rBottom && bottom
>= rTop){
return true;
} else {
return false;
}
}
}
Here is my main driver as well, because I might be doing something wrong here too.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
public class FreezeTagDriver {
public static final int CANVAS_SIZE = 800;
public static void main(String[] args) {
StdDraw.setCanvasSize(CANVAS_SIZE, CANVAS_SIZE);
StdDraw.setXscale(0, CANVAS_SIZE);
StdDraw.setYscale(0, CANVAS_SIZE);
Random rnd = new Random();
MovingRectangle[] recs;
recs = new MovingRectangle[5];
boolean frozen = false;
for (int i = 0; i < recs.length; i++) {
int xv = rnd.nextInt(4);
int yv = rnd.nextInt(4);
int x = rnd.nextInt(400);
int y = rnd.nextInt(400);
int h = rnd.nextInt(100) + 10;
int w = rnd.nextInt(100) + 10;
recs[i] = new MovingRectangle(x, y, w, h, xv, yv, CANVAS_SIZE);
}
while (true) {
StdDraw.clear();
for (int i = 0; i < recs.length; i++) {
recs[i].draw();
recs[i].move();
}
if (StdDraw.mousePressed()) {
for (int i = 0; i < recs.length; i++) {
double x = StdDraw.mouseX();
double y = StdDraw.mouseY();
if (recs[i].containsPoint(x, y)) {
recs[i].setFrozen(true);
}
}
}
for (int i = 0; i < recs.length; i++) {
//for 0
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[1])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[2])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[3])){
recs[0].setFrozen(false);
}
//for 1
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[2])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[3])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[4])){
recs[1].setFrozen(false);
}
//for 2
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[0])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[1])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[3])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[4])){
recs[2].setFrozen(false);
}
//for 3
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[0])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[1])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[2])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[4])){
recs[3].setFrozen(false);
}
//for 4
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[0])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[1])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[3])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[2]))
recs[4].setFrozen(false);
}
if (recs[0].isFrozen() && recs[1].isFrozen() &&
recs[2].isFrozen() && recs[3].isFrozen()
&& recs[4].isFrozen()) {
StdDraw.text(400, 400, "YOU WIN");
}
StdDraw.show(20);
}
}
}
Keep in mind you're using the OR operator here. So if right is less than rLeft, your intersector will return true. This isn't how it should work.
You need to check if right is INSIDE the rectangles bounds so to speak.
if(right <= rRight && right >= rLeft || the other checks here)
The above code checks if right is less than the rectangle's right, but also that the right is bigger than rectangle's left, which means it's somewhere in middle of the rectangle's left and right.
If this becomes too complicated you can simply use java's rectangle class, as it has the methods contains and intersects

Stuck with JavaFX GUI, how to draw/print after each state/calculation?

I am working on a GUI for a game of life implementation using javaFX. I am trying to draw each generation on the canvas after a one second delay, but my code does not do that. What happens is it gets a random zero generation, waits a second, generates the first generation, then waits another second generates the next one, and so on until it reaches the determined number of generations. Then after this whole proccess is done it draws the last generation only. I tried some experimenting with no luck, and now I am out of ideas. How can I get the program to draw after the calculatiion of each generation?
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class gui extends Application {
/////////////////////GUI SETUP PART/////////////////////////////////////////////
public int SquareSize = 16;
public int oldgrid [][];
public int newgrid [][];
public int ngens=5;
public int width = 10;
public int height = 10;
public int currentgen = 0;
public Group root;
public void start(Stage primaryStage) {
primaryStage.setTitle("Game of Life");
root = new Group();
oldgrid = new int [height][width];
newgrid = new int [height][width];
randomize();
Canvas canvas = new Canvas(500, 500);
GraphicsContext gc = canvas.getGraphicsContext2D();
run(gc);
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public void draw(GraphicsContext gc)
{
for(int y =0 ; y < getY() ; y++ )
{
for (int x = 0; x < getX() ; x++)
{
if(oldgrid[y][x] == 0)
{
gc.setFill(Color.WHITE);
gc.fillRect(x*SquareSize, y*SquareSize, SquareSize, SquareSize);
}
else if(oldgrid[y][x] == 1)
{
gc.setFill(Color.BLACK);
gc.fillRect(x*SquareSize, y*SquareSize, SquareSize, SquareSize);
}
}
}
}
////////////////////game of life rules part////////////////////////
public int getcurrentgen() {
return currentgen;
}
public int getX() {
return oldgrid[0].length;
}
public int getY() {
return oldgrid.length;
}
int Neighbours(int x, int y) //calculating neighbours
{
int neighbours = 0;
if (x > 0 && oldgrid[y][x - 1] == 1) {
neighbours++;
}
if (x < getX() - 1 && oldgrid[y][x + 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && x > 0 && oldgrid[y + 1][x - 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && x < getX() - 1 && oldgrid[y + 1][x + 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && oldgrid[y + 1][x] == 1) {
neighbours++;
}
if (y > 0 && x > 0 && oldgrid[y - 1][x - 1] == 1) {
neighbours++;
}
if (y > 0 && x < getX() - 1 && oldgrid[y - 1][x + 1] == 1) {
neighbours++;
}
if (y > 0 && oldgrid[y - 1][x] == 1) {
neighbours++;
}
return neighbours;
}
public void setup() // applying the rules
{
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
if (oldgrid[y][x] == 1) {
if (Neighbours(x, y) < 2) {
newgrid[y][x] = 0;
}
if (Neighbours(x, y) > 3) {
newgrid[y][x] = 0;
}
if (Neighbours(x, y) == 3 || Neighbours(x, y) == 2) {
newgrid[y][x] = 1;
}
}
if (oldgrid[y][x] == 0) {
if (Neighbours(x, y) == 3) {
newgrid[y][x] = 1;
}
}
}
}
}
public void run(GraphicsContext gc)
{
draw(gc);
while(currentgen < ngens)
{
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
setup();
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
oldgrid[y][x] = newgrid[y][x];
}
}
currentgen++;
draw(gc);
}
}
public void randomize() {
// randomizing dead(0) and live(1) cells
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
double tmp = Math.random();
if (tmp < 0.5) {
oldgrid[y][x] = 0;
} else {
oldgrid[y][x] = 1;
}
}
}
}
}

Java Applet Grid Game Flashing On Refresh/Keypress

I made a simple game on a grid in java that involves controlling a white square with the WASD keys. Whenever I press W,S,A, or D, the screen sometimes flickers before drawing the grid again. I am fairly new to coding, so the more you can dumb it down for me, the better.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
* DotGame.applet
*
* A simple game where the player controls a white circle with the WASD keys.
* - If the user moves his circle over a green circle, his score will go up by 1, and another red circle will spawn.
* - If the user moves his circle over a red circle, his score will go down by 1, and one less red circle will be generated.
* - There is no win condition, it is just a test game.
*
* #author -----------
* #version 11-9-2014
*/
public class DotGame extends Applet
implements KeyListener, MouseListener
{
int width,height;
int powerup = 1;
int click = 0;
int x,y;
final int size = 40;
int ox = size,oy = size;
int rx = 0, ry = 0;
int reddots = 0;
int red[][] = new int[1000][2];
String s = "";
int score = 0;
int DrawGrid = 0;
String sc = "";
int powerupdots = 1;
int yellow[][] = new int[1][2];
int powerupcounter = 0;
int shield = 0;
int blue[][] = new int[1][2];
public void init()
{
this.setSize(740,500);
width = 640;
height = 480;
setBackground( Color.black );
x = width/2;
y = height/2;
s = "CLICK TO START";
addMouseListener( this );
addKeyListener( this );
}
public void keyPressed( KeyEvent e ) { }
public void keyReleased ( KeyEvent e ) { }
public void keyTyped( KeyEvent e )
{
char c = e.getKeyChar();
String t = c+"";
//This will change the coordinates of the user-controlled circle by the size of the circle based on what button is pressed
if(powerupcounter > 0)
{
powerup = 2;
}
else if(powerupcounter == 0)
{
powerup = 1;
}
if( t.equalsIgnoreCase("w" )&& oy > 0+((powerup-1)*size))
{
oy = oy-(size*powerup);
}
else if( t.equalsIgnoreCase("s") && oy < height-(size*powerup))
{
oy = oy+(size*powerup);
}
else if( t.equalsIgnoreCase("a")&& ox > 0+((powerup-1)*size))
{
ox = ox-(size*powerup);
}
else if( t.equalsIgnoreCase("d") && ox < width-(size*powerup))
{
ox = ox+(size*powerup);
}
else if(t.equalsIgnoreCase("w" ) && oy == 0)
{
oy = height-(size*powerup);
}
else if(t.equalsIgnoreCase("s") && oy == height-size)
{
oy = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("a") && ox == 0)
{
ox = width-(size*powerup);
}
else if(t.equalsIgnoreCase("d") && ox == width-size)
{
ox = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("w") && oy == size && powerup ==2)
{
oy = height-size;
}
else if(t.equalsIgnoreCase("s") && oy == height -(size*powerup) && powerup ==2)
{
oy = 0;
}
else if(t.equalsIgnoreCase("a") && ox == size && powerup ==2)
{
ox = width-size;
}
else if(t.equalsIgnoreCase("d") && ox == width -(size*powerup) && powerup ==2)
{
ox = 0;
}
if(powerupcounter > 0)
{
powerupcounter--;
}
repaint();
e.consume();
}
public void mouseEntered( MouseEvent e) {}
public void mouseExited( MouseEvent e) {}
public void mousePressed( MouseEvent e) {}
public void mouseReleased( MouseEvent e) {}
public void mouseClicked( MouseEvent e)
{
if(click == 0)
{
randomYellow();
randomBlue();
DrawRandom();
x = e.getX();
y = e.getY();
s = "";
repaint();
e.consume();
click = 1;
}
}
public void CheckScore()
{
if(ox == rx && oy == ry)
{
score++;
reddots+=10;
DrawRandom();
}
}
public void DrawRandom()
{
//The reason we divide by the size and then multiply after it is an int is to
//make sure that the random circle drawn is in the same base as the size of the circle,
//so that the player's circle can move directly over it, and not be of by a fraction
//of the predetermined size.
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
while(rx == ox && ry == oy)
{
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
}
for(int y = 0 ; y < reddots ; y++)
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
while(red[y][0] == rx && red[y][1] == ry || red[y][0] == yellow[0][0] && red[y][1] == yellow[0][1]
|| red[y][0] == ox && red[y][1] == oy || red[y][0] == blue[0][0] && red[y][1] == blue[0][1])
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
}
}
}
public void randomYellow()
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
while(yellow[0][0] == rx && yellow[0][1] == ry)
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void randomBlue()
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
while(blue[0][0] == rx && blue[0][1] == ry || blue[0][0] == yellow[0][0] && blue[0][1] == yellow[0][1])
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void CheckDeath()
{
for(int y = 0 ; y < reddots ; y++)
{
if(ox == red[y][0] && oy == red[y][1] && shield == 0)
{
score--;
reddots--;
DrawRandom();
}
else if(ox == red[y][0] && oy == red[y][1] && shield !=0)
{
shield--;
DrawRandom();
}
}
}
public void CheckPowerup()
{
for(int y = 0 ; y < powerupdots ; y++)
{
if(ox == yellow[y][0] && oy == yellow[y][1])
{
powerupcounter += 10;
randomYellow();
}
}
}
public void CheckShield()
{
if(ox == blue[0][0] && oy == blue[0][1] && shield < 5)
{
shield++;
randomBlue();
}
else if(ox == blue[0][0] && oy == blue[0][1] && shield >= 5)
{
randomBlue();
}
}
public void CheckWin( Graphics g )
{
g.setColor(Color.black);
g.fillRect(0,0,width,height);
while(1 == 1)
{
g.drawString( "YOU WIN" , width/2, height/2);
}
}
public void paint( Graphics g )
{
CheckScore();
if(score == 20)
{
CheckWin(g);
}
CheckDeath();
CheckPowerup();
CheckShield();
DrawGrid(g);
g.setColor(Color.yellow);
g.fillRect(yellow[0][0],yellow[0][1],size+1,size+1);
g.setColor(Color.red);
for(int y = 0; y < reddots ; y++)
{
g.fillRect(red[y][0],red[y][1],size+1,size+1);
}
sc = ""+score;
//Draw user
g.setColor(Color.white);
g.fillRect(ox,oy,size+1,size+1);
//Draw shield around user if they have shields (max 5)
if(shield >= 1)
{
g.setColor(Color.blue);
g.fillRect(ox,oy,size+1,5);
g.fillRect(ox,oy,5,size+1);
g.fillRect(ox,oy+size-4,size+1,5);
g.fillRect(ox+size-4,oy,5,size+1);
}
//Draw green tile
g.setColor(Color.green);
g.fillRect(rx,ry,size+1,size+1);
//Draw shield tile
g.setColor(Color.blue);
g.fillRect(blue[0][0],blue[0][1],size+1,size+1);
g.setColor( Color.green );
g.drawString( s, x, y );
g.drawString( "Score : "+sc, 650, 20);
g.drawString( "Powerups : "+powerupcounter, 650, 40);
g.drawString( "Red Dots : "+reddots, 650,60);
g.drawString( "Shield : "+shield,650,80);
}
public void DrawGrid( Graphics g )
{
g.setColor(Color.orange);
for(int x = 0 ; x <= width ; x += size)
{
g.drawLine(x,0,x,height);
}
for(int y = 0 ; y <= height ; y+= size)
{
g.drawLine(0,y,width,y);
}
}
}
My advice is to move as much of your calculation as possible into methods called from your keypress events, and keep your paint() method as short and direct as possible. Don't do math inside your paint() method if you can help it - use your keypress method to build the picture of everything you need to paint before you call repaint(), and make your paint() method's only job to be to draw the current state of the board. Also, don't redraw the whole board anytime you don't have to. For instance, when moving from the current square to an empty square, all you should draw is a black square over your previous position, and a new user square in the new position. When hitting a yellow or blue square, all you need to draw is the new yellow or blue square (and update the appropriate status messages). You only need to redraw the whole board when hitting a red or green square.

keeping sprites from colliding java

I am making a game in java and I have most of it done. However, one of the last bugs i need to fix is that enemy sprites can overlap each other and spawn on top of one another off screen. I want to make it so if enemy sprites collide they can only touch but not overlap. here is the code for the enemy class.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Enemy extends Base {
int x;
int y;
int velx = -2;
int vely = 0;
public Enemy(int x, int y) {
super(x,y);
this.x = x;
this.y = y;
}
public void update() {
movement();
x += velx;
y += vely;
if (x < - 15) {
x = -15;
movement();
}
if (x > 1100) {
x = 1100;
movement();
}
if (y > 660) {
y = 660;
movement();
}
if (y < 10) {
y = 10;
movement();
}
}
public void draw(Graphics g) {
g.drawImage(getEnemyImage(), x, y, null);
}
public static Image getEnemyImage(){
ImageIcon ic = new ImageIcon("enemy.gif");
return ic.getImage();
}
public Rectangle getBounds(){
return new Rectangle(x, y, getEnemyImage().getWidth(null), getEnemyImage().getHeight(null));
}
public void checkColision(){
ArrayList<Base> enemies = GamePanel.getEnemyList();
if (x <= 0) {
velx = 2;
}
if (x >= 1096) {
velx = -2;
}
for (int a = 0; a < enemies.size(); a++) {
Base temp = GamePanel.enemy.get(a);
if (getBounds().intersects(temp.getBounds())) {
// where the collision check should happen.
}
}
}
public void movement(){
if (y > 16) {
if (x > GamePanel.p.getX()) {
velx = - 2;
}
if (x < GamePanel.p.getX()) {
velx = 2;
}
if (y > GamePanel.p.getY()) {
vely = -2;
}
if (y < GamePanel.p.getY()) {
vely = 2;
}
}
}
}
and this is where the enemies are spawned.
for (int a = 0; a < enemy_amount; a++) {
space += 50;
int rand = (int)(Math.random() * 2) + 1;
if (rand == 1) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 1250 + space;
y = 500;
}
if (randp == 2) {
x = 1250 + space;
y = 100;
}
enemy.add(new Enemy(x,y));
}
if (rand == 2) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 250;
y = -100 - space;
}
if (randp == 2) {
x = 850;
y = -100 - space;
}
enemy.add(new Enemy2(x,y));
}
}
any help would be great because i am really stuck.

Categories