The program was running fine before I put the Rectangle2D objects in an ArrayList, except that whenever I changed directions, the snake would just rotate rather than bend. Now the snake does not even show up, and my console gives me the error, as provided by Mad Programmer:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException:
Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
I know the issue is related to the ArrayLists, but how do I fix it?
Here is my class:
public class Display extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(1, this);
double xCoord = 50;
double yCoord = 50;
double xvel = 0;
double yvel = .01;
double ranx, xtemp;
double rany, ytemp;
int eaten = 0;
ArrayList<Rectangle2D> rects = new ArrayList<Rectangle2D>();
ArrayList<Double> xloc = new ArrayList<Double>();
ArrayList<Double> yloc = new ArrayList<Double>();
public Display(int xsize, int ysize) {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
xtemp = xsize;
ranx = (xtemp - 15) * Math.random();
ytemp = ysize;
rany = (ytemp - 15) * Math.random();
formSnake();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Adds snake
g2.setColor(Color.YELLOW);
for (int i = 0; i < rects.size(); i++) {
g2.fill(rects.get(i));
}
// Adds fruit at random location
g2.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(ranx, rany, 15, 15));
setBackground(Color.BLACK);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
// Replaces each rectangle location with one before it
for (int i = rects.size() - 1; i > 0; i--) {
xloc.set(i, xloc.get(i - 1));
yloc.set(i, yloc.get(i - 1));
}
// Sets new head location
xloc.set(0, xloc.get(0) + xvel);
yloc.set(0, yloc.get(0) + yvel);
getEaten();
}
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < rects.size(); i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
// Adds 1 2DRectangle to the front of the snake every time it eats
public void extend() {
// Vertical
if (xvel == 0) {
if (yvel <= 0) { // Up
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) - 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Down
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) + 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
// Horizontal
else if (yvel == 0) {
if (xvel <= 0) { // Left
xloc.add(xloc.get(xloc.size() - 1) - 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Right
xloc.add(xloc.get(xloc.size() - 1) + 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
}
public void getEaten() {
if (Math.abs(xCoord - ranx) < 15 && Math.abs(yCoord - rany) < 15) {
rany = ytemp * Math.random();
ranx = xtemp * Math.random();
eaten++;
extend();
}
}
//Directions
public void up() {
yvel = -0.5;
xvel = 0;
}
public void down() {
yvel = 0.5;
xvel = 0;
}
public void left() {
xvel = -0.5;
yvel = 0;
}
public void right() {
xvel = 0.5;
yvel = 0;
}
//Just for testing purposes
public void stop() {
xvel = 0;
yvel = 0;
}
//Direction implementation
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP || code == KeyEvent.VK_NUMPAD8) {
up();
}
if (code == KeyEvent.VK_DOWN || code == KeyEvent.VK_NUMPAD2) {
down();
}
if (code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_NUMPAD6) {
right();
}
if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_NUMPAD4) {
left();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
You seem to be getting a
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
At xloc.set(0, xloc.get(0) + xvel);, because there are no elements the xloc List
Change your formSnake method to do exactly what it says...// Adds initial 3 2DRectangles to snake at start of game instead of using rects.size(), which will be 0 when it's called...
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < 3; i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
Related
As a beginner in Java, I'm working on a project of Space Invaders. Looking to add more levels.
private void LevelInit() {
aliens = new ArrayList<>();
int currentLevel = 1;
if (currentLevel == 1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
//System.out.println(currentLevel);
}
}
}
else if (currentLevel == 2) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
// System.out.println(currentLevel);
}
}
}
else if (currentLevel == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
//System.out.println(currentLevel);
}
}
}
player = new Player();
bullet = new Bullet();
}
This function is the logic behind the code that initializes the game and gets called by the constructor. The simple way of adding levels is adding more Aliens.
This is how it looks after being updated from yesterday, levels are being added but the arraylists are being stuck together. Like the 12 - 16 - 24 aliens are together printed, some spaceships take 1 hit some 2 and some 3 and when they are all destroyed system give message of You passed level 1 and 2 and 3 together which is confusing me why are they bound together like that and not being passed.
And I can't figure it out. Also,
private void update() {
if (deaths == 12) {
inGame = false;
timer.stop();
message = "Next Level!";
}
// player
player.act();
// shot
if (bullet.isVisible()) {
int shotX = bullet.getX();
int shotY = bullet.getY();
for (Alien alien : aliens) {
int alienX = alien.getX();
int alienY = alien.getY();
if (alien.isVisible() && bullet.isVisible()) {
if (shotX >= (alienX)
&& shotX <= (alienX + Constants.ALIEN_WIDTH)
&& shotY >= (alienY)
&& shotY <= (alienY + Constants.ALIEN_HEIGHT)) {
var ii = new ImageIcon(explImg);
alien.setImage(ii.getImage());
alien.setDying(true);
deaths++;
bullet.die();
}
}
}
int y = bullet.getY();
y -= 4;
if (y < 0) {
bullet.die();
} else {
bullet.setY(y);
}
}
// aliens
for (Alien alien : aliens) {
int x = alien.getX();
if (x >= Constants.BOARD_WIDTH - Constants.BORDER_RIGHT && direction != -1) {
direction = -1;
for(Alien a2 : aliens) {
a2.setY(a2.getY() + Constants.GO_DOWN);
}
}
if (x <= Constants.BORDER_LEFT && direction != 1) {
direction = 1;
for(Alien a : aliens) {
a.setY(a.getY() + Constants.GO_DOWN);
}
}
}
for(Alien alien : aliens) {
if (alien.isVisible()) {
int y = alien.getY();
if (y > Constants.GROUND - Constants.ALIEN_HEIGHT) {
inGame = false;
message = "Invasion!";
}
alien.act(direction);
}
}
// bombs
var generator = new Random();
for (Alien alien : aliens) {
int shot = generator.nextInt(15);
Alien.Bomb bomb = alien.getBomb();
if (shot == Constants.CHANCE && alien.isVisible() && bomb.isDestroyed()) {
bomb.setDestroyed(false);
bomb.setX(alien.getX());
bomb.setY(alien.getY());
}
int bombX = bomb.getX();
int bombY = bomb.getY();
int playerX = player.getX();
int playerY = player.getY();
if (player.isVisible() && !bomb.isDestroyed()) {
if (bombX >= (playerX)
&& bombX <= (playerX + Constants.PLAYER_WIDTH)
&& bombY >= (playerY)
&& bombY <= (playerY + Constants.PLAYER_HEIGHT)) {
var ii = new ImageIcon(explImg);
player.setImage(ii.getImage());
player.setDying(true);
bomb.setDestroyed(true);
}
}
if (!bomb.isDestroyed()) {
bomb.setY(bomb.getY() + 1);
if (bomb.getY() >= Constants.GROUND - Constants.BOMB_HEIGHT) {
bomb.setDestroyed(true);
}
}
}
}
This function is to update the game whenever anything happens. The code is made from a bunch of YouTube videos and GitHubs, so excuse the copying if you see any.
I need to create new levels by simply adding more aliens, tried using a for loop but that resulted in either the aliens move faster or the bullet doesn't destroy an alien, it just hits.
Board class:
public class Board extends JPanel {
private Dimension d;
private List<Alien> aliens;
private Player player;
private Bullet bullet;
private int level;
private int direction = -1;
private int deaths = 0;
private boolean inGame = true;
private String explImg = "src/images/explosion.png";
private String message = "Game Over";
private Timer timer;
public Board() {
initBoard();
gameInit();
LevelInit();
}
private void initBoard() {
addKeyListener(new TAdapter());
setFocusable(true);
d = new Dimension(Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
setBackground(Color.black);
timer = new Timer(Constants.DELAY, new GameCycle());
timer.start();
gameInit();
}
private void gameInit() {
aliens = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j,
Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
player = new Player();
bullet = new Bullet();
}
private void LevelInit() {
inGame = true;
timer.start();
int level = 1;
if (aliens.isEmpty()) {
level++;
int AlienCount;if(level == 2) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
} else if (level == 3) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
var alien = new Alien(Constants.ALIEN_INIT_X + 18 * j, Constants.ALIEN_INIT_Y + 18 * i);
aliens.add(alien);
}
}
}
}
player = new Player();
bullet = new Bullet();
}
private void drawAliens(Graphics g) {
for (Alien alien : aliens) {
if (alien.isVisible()) {
g.drawImage(alien.getImage(), alien.getX(), alien.getY(), this);
}
if (alien.isDying()) {
alien.die();
}
}
}
private void drawPlayer(Graphics g) {
if (player.isVisible()) {
g.drawImage(player.getImage(), player.getX(), player.getY(), this);
}
if (player.isDying()) {
player.die();
inGame = false;
}
}
private void drawShot(Graphics g) {
if (bullet.isVisible()) {
g.drawImage(bullet.getImage(), bullet.getX(), bullet.getY(), this);
}
}
private void drawBombing(Graphics g) {
for (Alien a : aliens) {
Alien.Bomb b = a.getBomb();
if (!b.isDestroyed()) {
g.drawImage(b.getImage(), b.getX(), b.getY(), this);
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, d.width, d.height);
g.setColor(Color.green);
if (inGame) {
g.drawLine(0, Constants.GROUND,
Constants.BOARD_WIDTH, Constants.GROUND);
drawAliens(g);
drawPlayer(g);
drawShot(g);
drawBombing(g);
} else {
if (timer.isRunning()) {
timer.stop();
}
gameOver(g);
}
Toolkit.getDefaultToolkit().sync();
}
private void gameOver(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
g.setColor(new Color(0, 32, 48));
g.fillRect(50, Constants.BOARD_WIDTH / 2 - 30, Constants.BOARD_WIDTH - 100, 50);
g.setColor(Color.white);
g.drawRect(50, Constants.BOARD_WIDTH / 2 - 30, Constants.BOARD_WIDTH - 100, 50);
var small = new Font("Helvetica", Font.BOLD, 14);
var fontMetrics = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(message, (Constants.BOARD_WIDTH - fontMetrics.stringWidth(message)) / 2,
Constants.BOARD_WIDTH / 2);
}
private void update() {
if (deaths == aliens.size()) {
inGame = false;
timer.stop();
message = "Next Level!";
}
// player
player.act();
// shot
if (bullet.isVisible()) {
int shotX = bullet.getX();
int shotY = bullet.getY();
for (Alien alien : aliens) {
int alienX = alien.getX();
int alienY = alien.getY();
if (alien.isVisible() && bullet.isVisible()) {
if (shotX >= (alienX)
&& shotX <= (alienX + Constants.ALIEN_WIDTH)
&& shotY >= (alienY)
&& shotY <= (alienY + Constants.ALIEN_HEIGHT)) {
var ii = new ImageIcon(explImg);
alien.setImage(ii.getImage());
alien.setDying(true);
deaths++;
bullet.die();
}
}
}
int y = bullet.getY();
y -= 4;
if (y < 0) {
bullet.die();
} else {
bullet.setY(y);
}
}
// aliens
for (Alien alien : aliens) {
int x = alien.getX();
if (x >= Constants.BOARD_WIDTH - Constants.BORDER_RIGHT && direction != -1) {
direction = -1;
Iterator<Alien> i1 = aliens.iterator();
while (i1.hasNext()) {
Alien a2 = i1.next();
a2.setY(a2.getY() + Constants.GO_DOWN);
}
}
if (x <= Constants.BORDER_LEFT && direction != 1) {
direction = 1;
Iterator<Alien> i2 = aliens.iterator();
while (i2.hasNext()) {
Alien a = i2.next();
a.setY(a.getY() + Constants.GO_DOWN);
}
}
}
Iterator<Alien> it = aliens.iterator();
while (it.hasNext()) {
Alien alien = it.next();
if (alien.isVisible()) {
int y = alien.getY();
if (y > Constants.GROUND - Constants.ALIEN_HEIGHT) {
inGame = false;
message = "Invasion!";
}
alien.act(direction);
}
}
// bombs
var generator = new Random();
for (Alien alien : aliens) {
int shot = generator.nextInt(15);
Alien.Bomb bomb = alien.getBomb();
if (shot == Constants.CHANCE && alien.isVisible() && bomb.isDestroyed()) {
bomb.setDestroyed(false);
bomb.setX(alien.getX());
bomb.setY(alien.getY());
}
int bombX = bomb.getX();
int bombY = bomb.getY();
int playerX = player.getX();
int playerY = player.getY();
if (player.isVisible() && !bomb.isDestroyed()) {
if (bombX >= (playerX)
&& bombX <= (playerX + Constants.PLAYER_WIDTH)
&& bombY >= (playerY)
&& bombY <= (playerY + Constants.PLAYER_HEIGHT)) {
var ii = new ImageIcon(explImg);
player.setImage(ii.getImage());
player.setDying(true);
bomb.setDestroyed(true);
}
}
if (!bomb.isDestroyed()) {
bomb.setY(bomb.getY() + 1);
if (bomb.getY() >= Constants.GROUND - Constants.BOMB_HEIGHT) {
bomb.setDestroyed(true);
}
}
}
}
private void doGameCycle() {
update();
repaint();
}
private class GameCycle implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
doGameCycle();
}
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
int x = player.getX();
int y = player.getY();
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
if (inGame) {
if (!bullet.isVisible()) {
bullet = new Bullet(x, y);
}
}
}
}
}
}
As #JoachimSauer mentioned, your code needs refactoring. Here is one possible solution to your problem.
Additions
You will need two extra variables and one extra method.
Variables
1: int currentLevel - keeps track of the current level
2: boolean isLevelOver - keeps track if the current level is still active or not
Method
private void levelInit(int currentlevel)
{
aliens = new ArrayList<>();
int alienCount = //calculate alien count depending upon the current level
//Add aliens to aliens ArrayList
player = new Player();
bullet = new Bullet();
}
You have to provide implementation of how alienCount will be calculated depending upon currentLevel. The nested loop you used earlier to add aliens to aliens will also change. You have to make the loop dependent upon currentLevel.
Changes
Few of your methods will require some change.
public Board()
{
initBoard();
}
private void initBoard()
{
addKeyListener(new TAdapter());
setFocusable(true);
d = new Dimension(Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT);
setBackground(Color.black);
levelInit(currentLevel);
timer = new Timer(Constants.DELAY, new GameCycle());
timer.start();
}
private void update()
{
if (deaths == aliens.size())
{
isLevelOver = true;
currentLevel++;
message = "Next Level!";
return;
}
...
}
private void doGameCycle()
{
if (isLevelOver)
{
levelInit(currentLevel);
isLevelOver = false;
}
update();
repaint();
}
Notes
This is one of the possible ways to achieve what you want. There
might be other ways, probably better, but this is what I came up
with.
I tried to find as many additions and updation required in your code. However, I do not know its structure, you do. So there might be more additions or changes required.
I noticed you are were calling gameInit() in initBoard() and then again in Board() constructor. I think that might be unnecessary, please look into it.
You made one call to timer.stop() after setting isGame = false. This again might be unnecessary since you are already doing so inside doDrawing(...). Please also check that.
You should probably set a limit to either the levelCount() or max alien that can be on the screen since if you just keep on adding more aliens in each new level, they might fill up the entire screen.
I have provided many hints which should help you in your problem. If you still face any more problems or someone finds anything wrong with the answer, please comment.
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();
}
}
`
For my class I need to create a one player pong game. We need to use what we've learned so its simple code and the problem is, while the "while loop" is running, my Keydown thread doesn't seem to work. My teacher isn't helpful at all so that's why i'm here. Please help by only using methods and such that are used in my program.
I've tried moving the ball code into a run thread but i can never seem to actually get that thread running.
public class PongGame extends Applet {
int startup = 0;
int x = 400;
int y = 500;
int x2 = (int) (Math.random() * (600 + 1));
int y2 = (int) (Math.random() * (600 + 1));
int xVelocity = 1;
int yVelocity = 1;
int x2Velocity = 1;
int y2Velocity = 1;
int curry = 700;
int currx = 600;
int counter = 2;
#Override
public void init() {
setSize(1440, 900);
setBackground(Color.black);
setFont(new Font("Helvetica", Font.BOLD, 36));
}
#Override
public boolean keyDown(Event evt, int key) {
startup = startup + 1;
repaint();
if (key == Event.RIGHT) {
currx += 10;
}
if (key == Event.LEFT) {
currx -= 10;
}
if (currx == 1400) {
currx = 10;
}
if (currx == 20) {
currx = 1399;
}
repaint();
return false;
}
public void run(Graphics g) {
startup = 0;
while (counter > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
x += xVelocity;
y += yVelocity;
g.setColor(Color.blue);
g.fillRect(currx, curry, 300, 25);
g.setColor(Color.red);
g.fillOval(x, y, 30, 30);
for (int j = 0; j < 20000000; j++);
g.setColor(Color.black);
g.fillOval(x, y, 30, 30);
//Bounce the ball off the wall or paddle
if (x >= 1400 || x <= 0) {
xVelocity = -xVelocity;
}
if (y >= 800 || y <= 0) {
yVelocity = -yVelocity;
}
if (((y == 675)) && ((currx <= x) && (currx + 300) >= x)) {
yVelocity = -yVelocity;
y = y - 10;
repaint();
}
}
}
public void paint(Graphics g) {
if (startup == 0) {
g.setColor(Color.white);
g.drawString("Welcome To PONG", 0, 100);
g.drawString("Created by Caden Anton", 0, 200);
g.drawString("copyright May 3rd, 2019 ©", 0, 300);
g.drawString("Press any key to continue", 0, 400);
}
if (startup == 1) {
g.setColor(Color.white);
g.drawString("RULES:", 0, 100);
g.drawString("Press the arrwow keys to move the paddle", 0, 200);
g.drawString("Your objective is to keep the ball from touching the ground", 0, 300);
g.drawString("Once the ball hits the ground you lose the game", 0, 400);
}
if (startup >= 2) {
//Input Run thread start here.
}
}
}
I am trying to implement an undo / redo functionality in my line drawing/moving/deleting program. I am currently saving each line as a list of points and storing all the lines in a list. After every drawing/moving/deleting operation I will add the new list of lines to my buffer and increment the bufferIterator(counter) to be the last element of the buffer at every mouseReleased action. When I press ESC I am trying to make the current lines variable the previous list of lines and repaint, but the repaint part is not working. Does anyone have any idea what I am doing wrong ?
The code is here:
public class Kimp {
public static void main(String[] args) {
JFrame frame = new JFrame("Kimp!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.add(new CanvasPanel());
frame.setVisible(true);
}
}
class CanvasPanel extends JPanel {
private List<List<List<Point>>> buffer = new LinkedList<List<List<Point>>>();
private List<List<Point>> lines = new LinkedList<List<Point>>();
private List<Point> points = new LinkedList<Point>();
public boolean ctrlPressed;
public int bufferIterator = 0;
public int pressedX = -999;
public int pressedY = -999;
public int differenceX;
public int differenceY;
public List<Point> pressedLine = new LinkedList<Point>();
public List<Point> movedLine = new LinkedList<Point>();
public Color lineColor = Color.BLUE;
public CanvasPanel() {
this.setFocusable(true);
this.requestFocusInWindow();
addKeyListener(keyAdapter);
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.WHITE);
g2.setStroke(new BasicStroke(3));
g2.fillRect(0, 0, getWidth(), getHeight());
for (List<Point> line : lines) {
drawLine(line, g2);
}
drawLine(points, g2);
}
private void drawLine(List<Point> points, Graphics2D g2) {
if (points.size() < 2) return;
if (ctrlPressed) {
int lineS = points.size();
int lineP = pressedLine.size();
//Set the color to RED, if the line is being moved.
if (lineS == lineP) {
boolean first = comparePoints(points.get(0), pressedLine.get(0));
boolean second = comparePoints(points.get(lineS - 1), pressedLine.get(lineP - 1));
boolean third = comparePoints(points.get(lineS / 2), pressedLine.get(lineP / 2));
if (first && second && third) {
lineColor = Color.RED;
}
} else {
lineColor = Color.BLUE;
}
} else {
lineColor = Color.BLUE;
}
Point p1 = points.get(0);
for (int i=1, n=points.size(); i<n; i++) {
Point p2 = points.get(i);
g2.setColor(lineColor);
g2.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
private KeyAdapter keyAdapter = new KeyAdapter() {
#Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == ke.VK_ESCAPE) {
System.out.println("ESC PRESSED");
if (bufferIterator != 0) {
System.out.println("UNDOING!");
//UNDO
lines = new LinkedList<List<Point>>();
int index = bufferIterator - 1;
if (index >= 0) {
lines = buffer.get(index);
}
repaint();
} else {
int reply = JOptionPane.showConfirmDialog(null, "Do you want to exit?",
"Exit", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
} else if(ke.getKeyCode() == ke.VK_CONTROL) {
ctrlPressed = true;
} else if (ke.getKeyCode() == ke.VK_SPACE) {
System.out.println("REDOING");
//REDO
}
}
#Override
public void keyReleased(KeyEvent ke) {
if(ke.getKeyCode() == ke.VK_CONTROL) {
ctrlPressed = false;
}
}
};
private MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (ctrlPressed) {
if (e.isMetaDown()) {
Point pointPressed = e.getPoint();
for (int j=0, m=lines.size(); j<m; j++) {
List<Point> line = lines.get(j);
for (int i=0, n=line.size(); i<n; i++) {
Point pt = line.get(i);
//This is, to allow a small margin of missing, but still only take 1 point.
if (pointPressed.x - pt.x <= 1 && pointPressed.y - pt.y <= 1) {
//Only the first point will be "the point clicked".
if (pressedX == -999 && pressedY == -999) {
pressedX = pt.x;
pressedY = pt.y;
pressedLine = line;
}
}
}
}
for (int x = 0, r = lines.size(); x < r; x++) {
int lenA = lines.get(x).size();
int lenB = pressedLine.size();
if (lenA == lenB) {
boolean first = comparePoints(lines.get(x).get(0), pressedLine.get(0));
boolean second = comparePoints(lines.get(x).get(lenA - 1), pressedLine.get(lenB - 1));
boolean third = comparePoints(lines.get(x).get(lenA / 2), pressedLine.get(lenB / 2));
if (first && second && third) {
lines.remove(x);
buffer.add(lines);
repaint();
break;
}
}
}
} else {
Point pointPressed = e.getPoint();
for (int j=0, m=lines.size(); j<m; j++) {
List<Point> line = lines.get(j);
for (int i=0, n=line.size(); i<n; i++) {
Point pt = line.get(i);
//This is, to allow a small margin of missing, but still only take 1 point.
if (pointPressed.x - pt.x <= 1 && pointPressed.y - pt.y <= 1) {
//Only the first point will be "the point clicked".
if (pressedX == -999 && pressedY == -999) {
pressedX = pt.x;
pressedY = pt.y;
pressedLine = line;
}
}
}
}
}
} else {
points.add(e.getPoint());
repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
Point pointDragged = e.getPoint();
if (ctrlPressed) {
differenceX = pointDragged.x - pressedX;
differenceY = pointDragged.y - pressedY;
//Create the moved line
for (Point p : pressedLine) {
movedLine.add(new Point(p.x + differenceX , p.y + differenceY));
}
for (int i=0, n=lines.size(); i<n; i++) {
int lineS = lines.get(i).size();
int lineP = pressedLine.size();
//Choose 3 points in order to not go through all of them
boolean first = comparePoints(lines.get(i).get(0), pressedLine.get(0));
boolean second = comparePoints(lines.get(i).get(lineS - 1), pressedLine.get(lineP - 1));
boolean third = comparePoints(lines.get(i).get(lineS / 2), pressedLine.get(lineP / 2));
if (first && second && third) {
lines.set(i, movedLine);
pressedX = pressedX + differenceX;
pressedY = pressedY + differenceY;
pressedLine = movedLine;
movedLine = new LinkedList<Point>();
repaint();
break;
}
}
} else {
points.add(pointDragged);
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (points.size() > 1) {
lines.add(points);
points = new LinkedList<Point>();
}
//Add the current canvas to buffer
buffer.add(lines);
System.out.println("Buffer size:");
System.out.println(buffer.size() );
System.out.println(buffer.get(buffer.size() - 1));
bufferIterator = buffer.size() - 1;
pressedX = -999;
pressedY = -999;
}
};
public boolean comparePoints (Point p1, Point p2) {
if (p1.x == p2.x && p1.y == p2.y) {
return true;
}
return false;
}
}
The issue is that you are not adding new objects to the buffer. Each time it is a reference to the same List. So when you get the list at the correct index out of the buffer you get the same list as any other index.
To fix this create a copy of the lines list to add to the buffer instead of adding lines each time.
Something like:
buffer.add(lines);
lines = new LinkedList<List<Point>(lines);
So I'm trying to implement collision detection in my game and for some reason the collision isnt working properly.
public class ArenaKeys extends KeyAdapter {
arenaScreenBuild arena;
int xPos = 0, playerFace = 4;
int xPPos = 200, yPPos = 150;
int pX = 40, pY = 30;
AttackAshe aAtk = new AttackAshe();
int[][] mask = new int[400][92];
#SuppressWarnings("static-access")
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();// Get key pressed
if (keyCode == e.VK_RIGHT) {
playerFace = 4;
xPos += 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos -= 5;
} else if (keyCode == e.VK_LEFT) {
playerFace = 3;
xPos -= 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos += 5;
} else if (keyCode == e.VK_UP) {
playerFace = 2;
yPPos -= 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos += 5;
} else if (keyCode == e.VK_DOWN) {
playerFace = 1;
yPPos += 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos -= 5;
}
if (keyCode == e.VK_SPACE) {
aAtk.regArrow(arena.xPosition(), arena.yPosition());
arena.shoot(playerFace);
arena.xArrow = xPPos;
arena.yArrow = yPPos;
} else if (keyCode == e.VK_ESCAPE)
System.exit(0);
arena.moveArena(xPos);
arena.turnPlayer(playerFace);
arena.updateScreen(xPPos, yPPos);
}
public boolean checkBoundary(int x, int y) {
Rectangle t1 = new Rectangle(Turret.x, Turret.y, Turret.WIDTH,
Turret.HEIGHT);
Rectangle p = new Rectangle(pX, pY, Player.WIDTH, Player.HEIGHT);
if (t1.intersects(p))
// if (mask[x][y] == 0)
return false;
else
return true;
}
public static class Turret {
static int x = 168;
static int y = 40;
static final int WIDTH = 50;
static final int HEIGHT = 50;
}
public static class Player {
static final int WIDTH = 25;
static final int HEIGHT = 25;
}
public ArenaKeys(arenaScreenBuild arena) throws Exception {
this.arena = arena;
}
}
Approximately 20 units before the actual turret, the sprite stops being able to move any further. The sprite cannot go above or below the turret even if you go really high or really low.
What seems to be going wrong is that the sprite is colliding into the turret rectangle too early but I don't understand how that it possible. I draw the turret exactly 50 wide, 50 high at 168,40. The player is moving so it's x, y is different everytime but it's dimensions are 25 wide and 25 high.
The original turret is 126x111 approximately but I draw it as 50x50
25x25
public class arenaScreenBuild extends JPanel implements ActionListener {
String picPath = "pictures/";
String[] fileName = { "stageBridge.png", "turret.png", "Ashe.png",
"regArrow.png", "arenaScreen.png" };
ClassLoader cl = arenaScreenBuild.class.getClassLoader();
URL imgURL[] = new URL[5];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgTurret, imgPlayer, imgRegArrow, imgBorder;
Boolean[] ptFunc = new Boolean[3];
int PLAYER_INITIAL_X = 200, PLAYER_INITIAL_Y = 150;
int xPos = 0, xPFace = 150, yPFace = 0;
int xPPos = 200, yPPos = 150;
int xVal, yVal, xArrow, yArrow, xTemp, yTemp;
Timer space;
int counter, facePosition = 1;
public arenaScreenBuild() throws Exception {
for (int x = 0; x < 5; x++) {
imgURL[x] = cl.getResource(picPath + fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
imgTurret = tk.createImage(imgURL[1]);
imgPlayer = tk.createImage(imgURL[2]);
imgRegArrow = tk.createImage(imgURL[3]);
imgBorder = tk.createImage(imgURL[4]);
for (int x = 0; x < 3; x++)
ptFunc[x] = true;
space = new Timer(100, this);
}
public void updateScreen() {
repaint();
}
public void moveArena(int x) {
xPos = x;
}
public void updateScreen(int x, int y) {
xPPos = x;
yPPos = y;
repaint();
}
public boolean arrow() {
return (true);
}
public void turnPlayer(int face) {
if (face == 4) {
xPFace = 150;
} else if (face == 3) {
xPFace = 100;
} else if (face == 2) {
xPFace = 50;
} else if (face == 1) {
xPFace = 0;
}
if (yPFace == 50)
yPFace = 0;
else if (yPFace == 0)
yPFace = 50;
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 10, 30, 610, 490, xPos, 0, xPos + 600, 460, this);
g.drawImage(imgTurret, 850 - xPos, 200, 950 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgTurret, 1350 - xPos, 200, 1450 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgPlayer, xPPos, yPPos, 50 + (xPPos),
50 + (yPPos), xPFace, yPFace, xPFace + 50, yPFace + 50, this);
if (counter <= 5000 && counter > 0)
g.drawImage(imgRegArrow, xArrow, yArrow, this);
g.drawImage(imgBorder, 0, 0, 620, 600, 0, 0, 620, 600, this);
g.setColor(Color.WHITE);
g.drawString("x:" + (xPPos + xPos), 535, 525);
g.drawString("y:" + yPPos, 535, 545);
}
public int xPosition() {
xVal = xPPos + xPos;
return (xVal);
}
public int yPosition() {
yVal = yPPos;
return (yVal);
}
public void shoot(int i) {
facePosition = i;
xTemp = xPosition();
yTemp = yPosition();
space.start();
}
public void actionPerformed(ActionEvent e) {
counter++;
if (facePosition == 4) {
if (counter <= 5000) {
xArrow += 50;
}
}
else if (facePosition == 3) {
if (counter <= 5000) {
xArrow -= 50;
}
}
else if (facePosition == 2) {
if (counter <= 5000) {
yArrow -= 50;
}
}
else if (facePosition == 1) {
if (counter <= 5000) {
yArrow += 50;
}
}
if (xArrow == (xTemp + 100)) {
counter = 0;
space.stop();
}
updateScreen();
}
}
Turns out that my values for the x position were wrong. Also due to my previous boundary code, there were still remenants of it which messed me up therefore not allowing me to see the problem sooner.
For any one looking for how to make the collision detection boundary, just make 2 rectangles and use the
Rectangle rect1 = new Rectangle(topLeftX, topLeftY, rectangleWidth,rectangleHeight);
Rectangle rect2 = new Rectangle(topLeftX, topLeftY, rectangleWidth, rectangleHeight);
if (rect1.intersects(rect2))
//enter code to do if it intersects here