Adding KeyListener in Java - java

This a small game. Here I made 2 rectangles of same size. I want to move them whenever a person presses a key on keyboard. But I dont know how to add KeyListener. I had looked through previous answers here but I couldn't catch my mistake. I even searched the google but no clue. This is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class PongGame extends JComponent implements ActionListener {
int ballX = 200;
int ballY = 340;
short ballX_Direction = 1;
short ballY_Direction = 1;
static int Direction1 = 300;
static int Direction2 = 300;
private static keyListener move;
public static void main(String[] args) {
JFrame frame = new JFrame("Pong Game");
PongGame game = new PongGame();
frame.add(game);
frame.pack();
frame.setSize(900,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
Timer t = new Timer(2,game);
t.start();
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0,242,237));
g.fillRect(0,0,900,700);
g.setColor(Color.black);int a = 60;
for(int i = 1;i<=5;i++) {
g.fillRect(444,0+a,12,65);
a = a+125;
}
g.setColor(Color.blue);
g.fillRect(100,Direction2,15,100);
g.fillRect(770,Direction1,15,100);
g.setColor(Color.red);
g.fillOval(ballX,ballY,20,20);
repaint();
}
public void actionPerformed(ActionEvent e) {
ballX = ballX + ballX_Direction;
ballY = ballY + ballY_Direction;
if(ballY >= 660) ballY_Direction = -1;
if(ballY <= 0) ballY_Direction = 1;
if(ballX >= 444-20 && ballY >= 60-20 && ballX <= 444-20 && ballY <= 185-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 185-20 && ballX <= 444-20 && ballY <= 250-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 250-20 && ballX <= 444-20 && ballY <= 375-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 375-20 && ballX <= 444-20 && ballY <= 500-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 500-20 && ballX <= 444-20 && ballY <= 625-20) {
ballX_Direction = -1;
}
repaint();
}
}
class keyListener implements KeyListener {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP)
{
PongGame.Direction1 = PongGame.Direction1 - 25
}
if(key == KeyEvent.VK_DOWN)
{
PongGame.Direction1 = PongGame.Direction1 - 25;
}
if(key == '1')
{
PongGame.Direction2 -= 25;
}
if(key == '4')
{
PongGame.Direction2 += 25;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}

JFrame has a method for that:
frame.addKeyListener(new keyListener());
It needs to be added to a GUI part, in particular a part that has focus, since that is the thing the OS tells about input.

Related

My maze does not block character movement once it gets past the first tile

I currently have a maze project that is built of four tiles that form a loop when moving around to create an endless universe. Initially when inputting character blocking abilities, my second maze tile (the tile directly to the left of the character starting tile) displayed the blocking program one block off. The further you would move to the left onto the initial tile and back to the second tile, the more the character would be blocked off from the original tile. I assumed the problem lied within the tile placement, as the character would switch tiles, they would be one off. I altered my tile coordinates and size which somehow created a new problem. Now, the initial starting tile blocks appropriately, but once the character enters another tile, the blocking no longer works at all and the character is able to just proceed in an infinite loop around the maze. Attached is two classes: InTheDark (the class that calls the AppWindow) and AppWindow (the class consisting of the methods that develop the maze and the flashlight capabilities - they were commented out for the purpose of better access to the game). Some segments of code are commented out for the reason that they are functioning, but have no affect on the background. Could someone please help me on figuring out where the error is coming from?
This code contains InTheDark and AppWindow.
import java.text.DecimalFormat;
import java.applet.*;
import java.util.Random;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.Graphics2D.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioInputStream;
public class InTheDark
{
public static void main(String args[])
{ //launches the frame and timer events
int winWid = 500;
int winHei = 500;
AppWindow runner = new AppWindow(winWid,winHei);
runner.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}});
runner.setSize(winWid,winHei);
runner.show();
}
}
class AppWindow extends Frame implements KeyListener
{
int wid=0; //size of display window wid
int hei=0; //size of display window height
Image virtualMem;
Graphics gBuffer;
Image mazeBackgroundCenter;
Image mazeBackgroundElse;
Image character;
Graphics2D g2D;
int cx, cy;
int bx1, by1;
int bx2, by2;
int bx3, by3;
int bx4, by4;
int[][] maze11 = {{1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,0,0},
{1,0,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,1,0,0,1,1},
{1,0,1,1,0,1,1,1,0,1,1},
{0,0,0,1,0,0,0,0,0,1,1},
{1,1,0,1,1,1,1,1,1,1,1},
{1,1,0,0,0,0,1,1,1,1,1},
{1,1,0,1,1,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1}};
int[][] maze22 = {{1,1,1,0,1,1,1,1,1,1,1},
{0,0,0,0,0,0,1,1,1,1,1},
{1,1,0,1,1,0,1,1,0,1,1},
{1,0,0,1,1,0,0,0,0,1,1},
{1,1,0,1,1,1,1,0,1,1,1},
{1,1,0,0,0,0,1,0,0,0,0},
{1,1,1,1,1,0,1,1,0,1,1},
{1,0,0,0,0,0,1,1,1,1,1},
{1,1,1,0,1,0,0,0,0,1,1},
{1,1,1,1,1,1,1,1,0,1,1}};
int[][] maze33 = {{1,1,1,1,1,1,1,1,1,1,1},
{0,0,1,0,1,1,0,1,1,1,1},
{1,0,0,0,1,1,0,0,1,1,1},
{1,0,1,1,1,1,0,1,1,1,1},
{1,0,0,0,1,1,0,1,1,1,1},
{1,0,1,0,0,0,0,1,1,1,1},
{1,0,1,1,1,1,1,0,0,0,0},
{1,0,1,0,0,0,1,0,1,1,1},
{1,0,0,0,1,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1}};
int[][] maze44 = {{1,1,1,1,1,1,1,0,1,1,1},
{1,0,1,1,1,1,0,0,0,0,0},
{1,0,0,0,1,1,1,1,0,1,1},
{1,1,1,0,0,0,1,1,0,1,1},
{1,1,1,1,1,0,1,0,0,1,1},
{1,1,0,0,0,0,1,0,1,1,1},
{0,0,0,1,1,0,0,0,1,1,1},
{1,0,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,1},
{1,1,1,0,1,1,1,1,1,1,1}};
int[] charpos;
String line = null;
int batterywidth;
boolean flashlight;
boolean left,right,up,down;
public AppWindow(int width, int height)
{
virtualMem = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
gBuffer = virtualMem.getGraphics();
wid = width;
hei = height;
batterywidth = 40;
g2D = (Graphics2D)gBuffer;
flashlight = false;
charpos = new int[3];
charpos[0] = 1;
charpos[1] = 4;
charpos[2] = 4;
cx = 225;
cy = 225;
bx1 = 0;
by1 = 0;
bx2 = -500;
by2 = 0;
bx3 = 0;
by3 = -500;
bx4 = -500;
by4 = -500;
left = true;
right = true;
up = true;
down = true;
addKeyListener(this);
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
updateBackground();
placeCharacter();
if(charpos[0] == 1)
{
canMoveLeft(maze11);
canMoveRight(maze11);
canMoveUp(maze11);
canMoveDown(maze11);
}
if(charpos[0] == 2)
{
canMoveLeft(maze22);
canMoveRight(maze22);
canMoveUp(maze22);
canMoveDown(maze22);
}
if(charpos[0] == 3)
{
canMoveLeft(maze33);
canMoveRight(maze33);
canMoveUp(maze33);
canMoveDown(maze33);
}
if(charpos[0] == 4)
{
canMoveLeft(maze44);
canMoveRight(maze44);
canMoveUp(maze44);
canMoveDown(maze44);
}
/*if(batterywidth >= 1)
{
theLights();
if(batterywidth == 15)
{
gBuffer.setColor(Color.white);
gBuffer.drawString("Looks like you are getting close to running out of batteries.",50,470);
gBuffer.drawString("Look around and see if you can find any around the maze.",50,480);
}
battery();
}
if(batterywidth < 1)
{
flashlight = false;
theLights();
gBuffer.setColor(Color.white);
gBuffer.drawString("You are out of batteries. Try finding some around the maze.",50,470);
gBuffer.drawString("They will be the only things you can see in the dark.",50,480);
battery();
}
extraBatteries();*/
g.drawImage(virtualMem, 0, 0, this);
repaint();
}
public void extraBatteries()
{
}
public void theLights()
{
/*Color blck = new Color(0,0,0,240);
Rectangle2D.Double darkness = new Rectangle2D.Double(0,0,500,500);
Area glow = new Area(darkness);
if(flashlight)
{
Ellipse2D.Double light = new Ellipse2D.Double(cx-100,cy-100, 200, 200);
Area shiny = new Area(light);
glow.subtract(shiny);
Color yllw = new Color(189,183,107,200);
g2D.setPaint(yllw);
g2D.fill(shiny);
}
g2D.setPaint(blck);
g2D.fill(glow);*/
}
public void battery()
{
if(flashlight)
{
long time = System.currentTimeMillis();
if(time % 500 == 0)
{
batterywidth --;
}
}
Color drkgrn = new Color(0,128,0,200);
Color lghtgrn = new Color(154,205,50,200);
Color yellow = new Color(255,215,0,200);
Color red = new Color(255,0,0,200);
if(batterywidth <= 40)
{
g2D.setPaint(drkgrn);
if(batterywidth <= 30)
{
g2D.setPaint(lghtgrn);
if(batterywidth <= 20)
{
g2D.setPaint(yellow);
if(batterywidth <= 10)
{
g2D.setPaint(red);
}
}
}
}
Rectangle2D.Double grn = new Rectangle2D.Double(420,440,batterywidth,20);
Area battery = new Area(grn);
g2D.fill(battery);
}
public void canMoveLeft(int[][] maze00)
{
if(charpos[2]-1 > -1 && charpos[1] > 0 && charpos[1] < 11 && charpos[2] < 11)
{
if(maze00[charpos[1]][charpos[2]-1] == 0)
{
left = true;
}
else
{
left = false;
}
}
else
{
if(charpos[2]-1 < 0)
{
charpos[2] = 11;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
if(charpos[2] >= 10)
{
charpos[2] = 1;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveRight(int[][] maze00)
{
if(charpos[2]+1 < 12 && charpos[1] > 0 && charpos[1] < 11 && charpos[2] > 0)
{
if(maze00[charpos[1]][charpos[2]+1] == 0)
{
right = true;
}
else
{
right = false;
}
}
else
{
if(charpos[2]-1 < 0)
{
charpos[2] = 11;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
if(charpos[2] >= 10)
{
charpos[2] = 1;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveUp(int[][] maze00)
{
if(charpos[1]-1 > -1 && charpos[2] > 0 && charpos[2] < 11 && charpos[1] < 11)
{
if(maze00[charpos[1]-1][charpos[2]] == 0)
{
up = true;
}
else
{
up = false;
}
}
else
{
if(charpos[1]-1 < 0)
{
charpos[1] = 11;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
if(charpos[1] >= 10)
{
charpos[1] = 1;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveDown(int[][] maze00)
{
if(charpos[1]+1 < 12 && charpos[2] > 0 && charpos[2] < 11 && charpos[1] > 0)
{
if(maze00[charpos[1]+1][charpos[2]] == 0)
{
down = true;
}
else
{
down = false;
}
}
else
{
if(charpos[1]-1 < 0)
{
charpos[1] = 11;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
if(charpos[1] >= 10)
{
charpos[1] = 1;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
}
}
public void updateBackground()
{
if(bx1 > 500)
{
bx1 = -500;
bx3 = -500;
}
if(bx2 > 500)
{
bx2 = -500;
bx4 = -500;
}
if(bx1 < -500)
{
bx1 = 500;
bx3 = 500;
}
if(bx2 < -500)
{
bx2 = 500;
bx4 = 500;
}
if(by1 > 500)
{
by1 = -500;
by2 = -500;
}
if(by3 > 500)
{
by3 = -500;
by4 = -500;
}
if(by1 < -500)
{
by1 = 500;
by2 = 500;
}
if(by3 < -500)
{
by3 = 500;
by4 = 500;
}
drawFile(bx1,by1,maze11);
drawFile(bx2,by2,maze22);
drawFile(bx3,by3,maze33);
drawFile(bx4,by4,maze44);
}
public void drawFile(int x, int y, int[][] maze00)
{
for(int i = 0; i < maze00.length; i ++)
{
for(int ii = 0; ii < maze00[i].length; ii++)
{
if(maze00[i][ii] == 1)
{
gBuffer.setColor(Grfx.black);
}
if(maze00[i][ii] == 0)
{
gBuffer.setColor(Grfx.white);
}
gBuffer.fillRect(x + ii*50, y + i*50, 50, 50);
}
}
}
public void placeCharacter()
{
gBuffer.setColor(Grfx.red);
gBuffer.fillOval(cx-10,cy-10,20,20);
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
int buff1 = bx1;
if(left)
{
bx1+=50;
bx2+=50;
bx3+=50;
bx4+=50;
charpos[2]--;
}
}
if (key == KeyEvent.VK_RIGHT)
{
int buff1 = bx1;
if(right)
{
bx1-=50;
bx2-=50;
bx3-=50;
bx4-=50;
charpos[2]++;
}
}
if (key == KeyEvent.VK_DOWN)
{
if(down)
{
by1-=50;
by2-=50;
by3-=50;
by4-=50;
charpos[1] ++;
}
}
if (key == KeyEvent.VK_UP)
{
if(up)
{
by1+=50;
by2+=50;
by3+=50;
by4+=50;
charpos[1] --;
}
}
if (key == KeyEvent.VK_SPACE)
{
if(flashlight)
{
flashlight = false;
}
else
{
flashlight = true;
}
}
if (key == KeyEvent.VK_ESCAPE)
{
}
}
}

How to restart while loop in order to restart game?

I want the game to restart when the player pressed the y key on the keyboard after dying or getting hit by the small ball.
BoxX and BoxY are the coordinates for enemy balls
Ball holds the rectangle or hitbox for all the enemy balls
ReverseX and Y, IndexX and Y, and BallXchange and Y all have to do with the movement of the enemy balls.
Here is the code:
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.*;
import java.util.ArrayList;
import java.awt.Font;
import java.awt.Color;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class GameNotes extends JPanel implements KeyListener{
int x1=1;
int y1=1;
int ballx = 40;
int bally = 60;
boolean gameRunning = true;
BufferedImage image;
int windowx = 500;
int windowy = 500;
int score = 0;
int rectX = (int)(Math.random()*400)+30;
int rectY = (int)(Math.random()*400)+30;
int enemyX = (int)(Math.random()*300)+100;
int enemyY = (int)(Math.random()*250)+100;
int count = 1;
int num = 0;
boolean reverseX = false;
boolean reverseY = false;
boolean right = false;
boolean left = false;
boolean up = false;
boolean down = false;
ArrayList<Integer> BoxX = new ArrayList<Integer>();
ArrayList<Integer> BoxY = new ArrayList<Integer>();
ArrayList<Rectangle> Ball = new ArrayList<Rectangle>();
ArrayList<Integer> ReverseX = new ArrayList<Integer>();
ArrayList<Integer> ReverseY = new ArrayList<Integer>();
ArrayList<Integer> BallYchange = new ArrayList<Integer>();
ArrayList<Integer> BallXchange = new ArrayList<Integer>();
ArrayList<Integer> indexY = new ArrayList<Integer>();
ArrayList<Integer> indexX = new ArrayList<Integer>();
public GameNotes(){
setFocusable(true);
JFrame frame = new JFrame("GameDemo");
frame.setSize(windowx, windowy);
frame.add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
try{
image = ImageIO.read(new File("C:\\Users\\10021707\\Desktop\\Game\\b.jpg"));
}catch (Exception e){
System.out.println("image not found \n E000384JW29400119482938WJDI39");
}
game:
while(gameRunning){
try{
Thread.sleep(3);
}catch(Exception e){
System.out.println("error");
}
Rectangle r = new Rectangle (ballx,bally,20,20);
Rectangle r2 = new Rectangle (rectX,rectY,30,30);
Rectangle rE = new Rectangle (enemyX,enemyY,10,10);
if(count == 1){
BoxX.add(enemyX);
BoxY.add(enemyY);
Ball.add(rE);
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
count--;
}
//System.out.println("ReverseY" + ReverseY.size());
if(ballx >= 461)
ballx = 461;
if(ballx <= 0)
ballx = 0;
if(bally >= 432)
bally = 432;
if(bally <= 0)
bally = 0;
if(r.intersects(r2)){
score+=5;
rectX = (int)(Math.random()*400)+30;
rectY = (int)(Math.random()*400)+30;
enemyX = (int)(Math.random()*300)+50;
enemyY = (int)(Math.random()*300)+50;
BoxX.add(enemyX);
BoxY.add(enemyY);
int x = (int)(Math.random()*10)+1;
//System.out.println(x);
if(x > 5){
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
}
if(x <= 5){
ReverseY.add(1);
BallYchange.add(enemyY);
num++;
indexY.add(num);
}
Rectangle En = new Rectangle (enemyX,enemyY,10,10);
Ball.add(En);
//System.out.println(Ball);
}
for(int i = 0; i < Ball.size(); i++){
Rectangle w = new Rectangle (BoxX.get(i),BoxY.get(i),10,10);
Ball.set(i,w);
}
for(int i = 0; i < BoxX.size(); i++){
if(r.intersects(Ball.get(i))){
gameRunning = false;
}
}
//System.out.println(ReverseY);
for(int i = 0; i < ReverseX.size(); i++){
BallXchange.set(i,BallXchange.get(i)+ReverseX.get(i));
BoxX.set(indexX.get(i)-1,BallXchange.get(i));
if(BallXchange.get(i) >= 470 || BallXchange.get(i) <= 0){
ReverseX.set(i,ReverseX.get(i)*-1);
}
}
for(int i = 0; i < ReverseY.size(); i++){
BallYchange.set(i,BallYchange.get(i)+ReverseY.get(i));
BoxY.set(indexY.get(i)-1,BallYchange.get(i));
if(BallYchange.get(i) >= 445 || BallYchange.get(i) <= 0){
ReverseY.set(i,ReverseY.get(i)*-1);
}
}
if(right)
ballx++;
if(left)
ballx--;
if(up)
bally--;
if(down)
bally++;
repaint();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,null);
g.fillOval(ballx,bally,20,20);
g.fillRect(rectX,rectY,30,30);
for(int i = 0; i < BoxX.size(); i++){
g.fillOval(BoxX.get(i),BoxY.get(i),10,10);
}
if(!gameRunning){
g.setColor(getBackground());
g.clearRect(rectX,rectY,30,30);
g.fillRect(rectX,rectY,30,30);
for(int i = 0; i < BoxX.size(); i++){
g.clearRect(BoxX.get(i),BoxY.get(i),10,10);
g.fillOval(BoxX.get(i),BoxY.get(i),10,10);
g.fillRect(BoxX.get(i),BoxY.get(i),10,10);
}
BoxX.clear();
BoxY.clear();
Ball.clear();
ReverseX.clear();
ReverseY.clear();
BallXchange.clear();
BallYchange.clear();
indexX.clear();
indexY.clear();
g.setColor(Color.BLACK);
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Game Over", 165, 200);
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString("Do you want to play again?", 100, 230);
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.drawString("(y or n)", 200, 250);
}
if(gameRunning){
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));;
g.drawString("Score: "+score, 100, 450);
}
/*for(int i = 0; i < Ball.size(); i++){
g.fillRect((int)Ball.get(i).getX(),(int)Ball.get(i).getY(),10,10);
}*/
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT)
right = false;
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT)
left = false;
if(e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP)
up = false;
if(e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN)
down = false;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(gameRunning == false && key == e.VK_Y){
score = 0;
gameRunning = true;
}
if(e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT)
right = true;
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT)
left = true;
if(e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP)
up = true;
if(e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN)
down = true;
}
public void keyTyped(KeyEvent e){
}
public static void main (String [] samay){
GameNotes test = new GameNotes();
}
}
Any help would be appreciated!
As ordonezalex suggested in his comment you can take the while loop and put it in a method such as this:
public void runGame() {
while(gameRunning){
try{
Thread.sleep(3);
}catch(Exception e){
System.out.println("error");
}
Rectangle r = new Rectangle (ballx,bally,20,20);
Rectangle r2 = new Rectangle (rectX,rectY,30,30);
Rectangle rE = new Rectangle (enemyX,enemyY,10,10);
if(count == 1){
BoxX.add(enemyX);
BoxY.add(enemyY);
Ball.add(rE);
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
count--;
}
//System.out.println("ReverseY" + ReverseY.size());
if(ballx >= 461)
ballx = 461;
if(ballx <= 0)
ballx = 0;
if(bally >= 432)
bally = 432;
if(bally <= 0)
bally = 0;
if(r.intersects(r2)){
score+=5;
rectX = (int)(Math.random()*400)+30;
rectY = (int)(Math.random()*400)+30;
enemyX = (int)(Math.random()*300)+50;
enemyY = (int)(Math.random()*300)+50;
BoxX.add(enemyX);
BoxY.add(enemyY);
int x = (int)(Math.random()*10)+1;
//System.out.println(x);
if(x > 5){
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
}
if(x <= 5){
ReverseY.add(1);
BallYchange.add(enemyY);
num++;
indexY.add(num);
}
Rectangle En = new Rectangle (enemyX,enemyY,10,10);
Ball.add(En);
//System.out.println(Ball);
}
for(int i = 0; i < Ball.size(); i++){
Rectangle w = new Rectangle (BoxX.get(i),BoxY.get(i),10,10);
Ball.set(i,w);
}
for(int i = 0; i < BoxX.size(); i++){
if(r.intersects(Ball.get(i))){
gameRunning = false;
}
}
//System.out.println(ReverseY);
for(int i = 0; i < ReverseX.size(); i++){
BallXchange.set(i,BallXchange.get(i)+ReverseX.get(i));
BoxX.set(indexX.get(i)-1,BallXchange.get(i));
if(BallXchange.get(i) >= 470 || BallXchange.get(i) <= 0){
ReverseX.set(i,ReverseX.get(i)*-1);
}
}
for(int i = 0; i < ReverseY.size(); i++){
BallYchange.set(i,BallYchange.get(i)+ReverseY.get(i));
BoxY.set(indexY.get(i)-1,BallYchange.get(i));
if(BallYchange.get(i) >= 445 || BallYchange.get(i) <= 0){
ReverseY.set(i,ReverseY.get(i)*-1);
}
}
if(right)
ballx++;
if(left)
ballx--;
if(up)
bally--;
if(down)
bally++;
repaint();
}
}
Then replace the while loop with this:
runGame();
And each time you want to re-run the game you can use that again, as long as the boolean gameRunning is true.
There are a few things you would need to update in your code:
A. Create a boolean called programRunning and set it to true:
boolean gameRunning = true;
boolean programRunning = true;
B. Create a private void method called initGame() and place all the game initialization code there:
private void initGame()
{
x1=1;
y1=1;
ballx = 40;
bally = 60;
windowx = 500;
windowy = 500;
score = 0;
rectX = (int)(Math.random()*400)+30;
rectY = (int)(Math.random()*400)+30;
enemyX = (int)(Math.random()*300)+100;
enemyY = (int)(Math.random()*250)+100;
count = 1;
num = 0;
reverseX = false;
reverseY = false;
right = false;
left = false;
up = false;
down = false;
BoxX = new ArrayList<Integer>();
BoxY = new ArrayList<Integer>();
Ball = new ArrayList<Rectangle>();
ReverseX = new ArrayList<Integer>();
ReverseY = new ArrayList<Integer>();
BallYchange = new ArrayList<Integer>();
BallXchange = new ArrayList<Integer>();
indexY = new ArrayList<Integer>();
indexX = new ArrayList<Integer>();
}
C. Modify the following code under the section where you are assigning a JPG to the image variable:
try{
image = ImageIO.read(new File("C:\\Users\\10021707\\Desktop\\Game\\b.jpg"));
}catch (Exception e){
System.out.println("image not found \n E000384JW29400119482938WJDI39");
}
//CODE CHANGED BELOW THIS COMMENT
do {
initGame();
while (gameRunning) {
runGame();
}
} while (programRunning);
D. Create the runGame() method that contains all of your code within the while (gameRunning) loop:
private void runGame()
{
try{
Thread.sleep(3);
}catch(Exception e){
System.out.println("error");
}
Rectangle r = new Rectangle (ballx,bally,20,20);
Rectangle r2 = new Rectangle (rectX,rectY,30,30);
Rectangle rE = new Rectangle (enemyX,enemyY,10,10);
if(count == 1){
BoxX.add(enemyX);
BoxY.add(enemyY);
Ball.add(rE);
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
count--;
}
//System.out.println("ReverseY" + ReverseY.size());
if(ballx >= 461)
ballx = 461;
if(ballx <= 0)
ballx = 0;
if(bally >= 432)
bally = 432;
if(bally <= 0)
bally = 0;
if(r.intersects(r2)){
score+=5;
rectX = (int)(Math.random()*400)+30;
rectY = (int)(Math.random()*400)+30;
enemyX = (int)(Math.random()*300)+50;
enemyY = (int)(Math.random()*300)+50;
BoxX.add(enemyX);
BoxY.add(enemyY);
int x = (int)(Math.random()*10)+1;
//System.out.println(x);
if(x > 5){
ReverseX.add(1);
BallXchange.add(enemyX);
num++;
indexX.add(num);
}
if(x <= 5){
ReverseY.add(1);
BallYchange.add(enemyY);
num++;
indexY.add(num);
}
Rectangle En = new Rectangle (enemyX,enemyY,10,10);
Ball.add(En);
//System.out.println(Ball);
}
for(int i = 0; i < Ball.size(); i++){
Rectangle w = new Rectangle (BoxX.get(i),BoxY.get(i),10,10);
Ball.set(i,w);
}
for(int i = 0; i < BoxX.size(); i++){
if(r.intersects(Ball.get(i))){
gameRunning = false;
}
}
//System.out.println(ReverseY);
for(int i = 0; i < ReverseX.size(); i++){
BallXchange.set(i,BallXchange.get(i)+ReverseX.get(i));
BoxX.set(indexX.get(i)-1,BallXchange.get(i));
if(BallXchange.get(i) >= 470 || BallXchange.get(i) <= 0){
ReverseX.set(i,ReverseX.get(i)*-1);
}
}
for(int i = 0; i < ReverseY.size(); i++){
BallYchange.set(i,BallYchange.get(i)+ReverseY.get(i));
BoxY.set(indexY.get(i)-1,BallYchange.get(i));
if(BallYchange.get(i) >= 445 || BallYchange.get(i) <= 0){
ReverseY.set(i,ReverseY.get(i)*-1);
}
}
if(right)
ballx++;
if(left)
ballx--;
if(up)
bally--;
if(down)
bally++;
repaint();
}
E. Add this code to your keyPressed(KeyEvent e) method:
if (gameRunning == false && key == KeyEvent.VK_N)
{
programRunning = false;
System.exit(0); //Closes the application.
}
Just giving you the main idea :
do{
//All logic goes here
//At the end of the game take input from user in the form of 'Y|y' or 'N|n'
System.out.println("Do you want to continue : press 'Y' for yes and 'N' for no");
Scanner sc=new Scanner(System.in);
String choice=sc.nextLine();
} while(choice.equalsIgnoreCase("Y"))

Thread.sleep() and GUI

i just searched on the forum but I couldn't find anything that helps me.. My problem is the following : I was trying to create a little game in which you have to walk right in your friend's back in order to win, the game ends when one of them achieves this..
Here's a simple code I made to explain my problem
I have 3 classes in my application (which belong in the package code) :
Main
Game
Position
I have 9 .png in my application (which belong in the package img) :
0.png
j1_0.png
j1_1.png
j1_2.png
j1_3.png
j2_0.png
j2_1.png
j2_2.png
j2_3.png
Both packages are at the src root
First class :
package code;
public class Main{
public static Game game;
public static void main(String[] args){
game = new Game(8, 8);
}
}
Seconds class :
package code;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Game extends JFrame{
private Position j1, j2;
private JPanel panel;
private JLabel[][] grid;
private int largeur, hauteur;
public Game(int hauteur, int largeur){ // >= 2
super("Rattrape l'autre");
this.largeur = largeur;
this.hauteur = hauteur;
this.panel = new JPanel(new GridBagLayout());
this.add(this.panel);
this.grid = new JLabel[largeur][hauteur];
int x1 = (int) (Math.random() * largeur), y1 = (int) (Math.random() * hauteur), x2, y2;
do{
x2 = (int) (Math.random() * largeur);
y2 = (int) (Math.random() * hauteur);
}while(x2 == x1 && y2 == y1);
this.j1 = new Position(x1, y1, (int) (Math.random() * 4));
this.j2 = new Position(x2, y2, (int) (Math.random() * 4));
updatePanel();
this.setResizable(false);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
boolean over = false;
if(e.getKeyCode() == KeyEvent.VK_Z){
if(j1.getY() != 0 && !(j1.getY() == j2.getY() + 1 && j1.getX() == j2.getX())){
j1.goesUp();
}else if(j2.getDirection() == 0 && j1.getY() == j2.getY() + 1 && j1.getX() == j2.getX()){
over = true;
}
j1.turnUp();
}else if(e.getKeyCode() == KeyEvent.VK_D){
if(j1.getX() != largeur - 1 && !(j1.getX() == j2.getX() - 1 && j1.getY() == j2.getY())){
j1.goesRight();
}else if(j2.getDirection() == 1 && j1.getX() == j2.getX() - 1 && j1.getY() == j2.getY()){
over = true;
}
j1.turnRight();
}else if(e.getKeyCode() == KeyEvent.VK_S){
if(j1.getY() != hauteur - 1 && !(j1.getY() == j2.getY() - 1 && j1.getX() == j2.getX())){
j1.goesDown();
}else if(j2.getDirection() == 2 && j1.getY() == j2.getY() - 1 && j1.getX() == j2.getX()){
over = true;
}
j1.turnDown();
}else if(e.getKeyCode() == KeyEvent.VK_Q){
if(j1.getX() != 0 && !(j1.getX() == j2.getX() + 1 && j1.getY() == j2.getY())){
j1.goesLeft();
}else if(j2.getDirection() == 3 && j1.getX() == j2.getX() + 1 && j1.getY() == j2.getY()){
over = true;
}
j1.turnLeft();
}
if(e.getKeyCode() == KeyEvent.VK_UP){
if(j2.getY() != 0 && !(j2.getY() == j1.getY() + 1 && j2.getX() == j1.getX())){
j2.goesUp();
}else if(j1.getDirection() == 0 && j2.getY() == j1.getY() + 1 && j2.getX() == j1.getX()){
over = true;
}
j2.turnUp();
}else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
if(j2.getX() != largeur - 1 && !(j2.getX() == j1.getX() - 1 && j2.getY() == j1.getY())){
j2.goesRight();
}else if(j1.getDirection() == 1 && j2.getX() == j1.getX() - 1 && j2.getY() == j1.getY()){
over = true;
}
j2.turnRight();
}else if(e.getKeyCode() == KeyEvent.VK_DOWN){
if(j2.getY() != hauteur - 1 && !(j2.getY() == j1.getY() - 1 && j2.getX() == j1.getX())){
j2.goesDown();
}else if(j1.getDirection() == 2 && j2.getY() == j1.getY() - 1 && j2.getX() == j1.getX()){
over = true;
}
j2.turnDown();
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
if(j2.getX() != 0 && !(j2.getX() == j1.getX() + 1 && j2.getY() == j1.getY())){
j2.goesLeft();
}else if(j1.getDirection() == 3 && j2.getX() == j1.getX() + 1 && j2.getY() == j1.getY()){
over = true;
}
j2.turnLeft();
}
updatePanel();
if(over){
end();
}
}
#Override
public void keyReleased(KeyEvent e){}
#Override
public void keyTyped(KeyEvent e){}
});
}
public void updatePanel(){
GridBagConstraints c = new GridBagConstraints();
this.panel.removeAll();
for(int x = 0; x < largeur; x++){
for(int y = 0; y < hauteur; y++){
if(x == j1.getX() && y == j1.getY()){
this.grid[x][y] = new JLabel(new ImageIcon(Main.class.getResource("/img/j1_" + j1.getDirection() + ".png")));
}else if(x == j2.getX() && y == j2.getY()){
this.grid[x][y] = new JLabel(new ImageIcon(Main.class.getResource("/img/j2_" + j2.getDirection() + ".png")));
}else{
this.grid[x][y] = new JLabel(new ImageIcon(Main.class.getResource("/img/0.png")));
}
c.gridx = x;
c.gridy = y;
this.panel.add(this.grid[x][y], c);
}
}
this.panel.revalidate();
}
public void end(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
Main.game.dispose();
}
}
Third class :
package code;
public class Position{
private int x, y, direction;
public Position(int x, int y, int direction){
this.x = x;
this.y = y;
this.direction = direction;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
public int getDirection(){
return this.direction;
}
public void goesUp(){
this.y--;
}
public void goesRight(){
this.x++;
}
public void goesDown(){
this.y++;
}
public void goesLeft(){
this.x--;
}
public void turnUp(){
this.direction = 0;
}
public void turnRight(){
this.direction = 1;
}
public void turnDown(){
this.direction = 2;
}
public void turnLeft(){
this.direction = 3;
}
}
Finally, my problem is this one :
I wanted that, for example, when the Player 1 looks left and he's just on top of the Player 2, while the Player 2 looks down, if the player 1 moves down, it should wins the game, but AFTER displaying the Player 1 looking down.
I tried a lot of input o test, and it seems to work because when over is set to true, then the program goes in updatePanel() and then it launches end() which should sleep for 1 second and then dispose the frame.. but it doesn't, it does launch updatePanel() at the end, it update the value of j1 (as the previous algorithm, i mean the one that assignes values in function of the keyboard inputs, made him look down) but it doesn't display the new grid so, i'm lost :p
Thanks in advice I hope you got the problem, plus the algorithm is easy and not that long so it shouldn't be hard for you guys to understand it :)
should sleep for 1 second and then dispose the frame..
You can't use Thread.sleep() on the Event Dispatch Thread(EDT). This will cause the GUI to sleep which means it will not get repainted.
Instead you need to use a separate Thread, probably a SwingWorker. A SwingWorker will allow you to use Thread.sleep() and then you can publish results when you are finished sleeping.
Read the section from the Swing tutorial on Concurrency for more information and examples.

In my code I have a cube and it seems to skip along whenever a direction is just tapped

I am writing a code to practice for the AP test and in my code the cube I put will skip a large amount whenever a direction key is tapped but if it's tapped then I want it to not move.
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
class Cance extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
int x = 50, velX = 0, y = 200, velY = 0, x2 = 50, velX2 = 0, y2 = 500, velY2 = 0;
int copX = 0; int copY = 0;
public Cance(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 50, 50);
tm.start();
g.setColor(Color.GREEN);
g.fillRect(copX, copY, 50, 50);
}
public void actionPerformed(ActionEvent e){
x = x + velX;
y = y + velY;
}
public void keyPressed(KeyEvent e){
System.out.println("keyPressed");
int c = e.getKeyCode();
if(copX > x && copY > y){
copX -= x/100;
copY -= y/100;
}
if(copX > x && copY < y){
copX -= x/100;
copY += y/100;
}
if(copX < x && copY > y){
copX += x/100;
copY -= y/100;
}
if(copX < x && copY < y){
copX += x/100;
copY += y/100;
}
if(copX == x && copY < y){
copX += x/100;
copY += y/100;
}
if(copX == x && copY > y){
copX += x/100;
copY += y/100;
}
if(copX < x && copY == y){
copX += x/100;
copY += y/100;
}
if(copX > x && copY == y){
copX += x/100;
copY += y/100;
}
if(c == KeyEvent.VK_LEFT){
velX = -1;
velY = 0;
}
if(c == KeyEvent.VK_UP){
velX = 0;
velY = -1;
}
if(c == KeyEvent.VK_RIGHT){
velX = 1;
velY = 0;
}
if(c == KeyEvent.VK_DOWN){
velX = 0;
velY = 1;
}
int b = e.getKeyCode();
if(b == KeyEvent.VK_A){
velX2 = -1;
velY2 = 0;
}
if(b == KeyEvent.VK_W){
velX2 = 0;
velY2 = 0;
}
if(b == KeyEvent.VK_D){
velX2 = 1;
velY2 = 0;
}
if(b == KeyEvent.VK_S){
velX2 = 0;
velY2 = 0;
}
repaint();
}
public void keyReleased(KeyEvent e){
System.out.println("keyReleased");
}
public void keyTyped(KeyEvent e){
System.out.println("keyTyped");
}
}
public class RacesTester {
public static void main(String args[]){
JFrame wind = new JFrame();
wind.setBounds(50, 50, 600, 600);
wind.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wind.setVisible(true);
wind.setResizable(true);
wind.add(new Cance());
}
}

Why collision algorithm in my applet game does not work properly ?

This is my game project. It's very simple version of "Flappy Bird" and I have some serious problems with how the collisions algorithm works. I wrote 2 separate code fragments for collision, for wall1 and wall2. The problem begins when the ball is trying to go through a hole because somehow the program is detecting a collision with a wall. I'm almost positive that the collision algorithm was written correctly because I have been checking it all day.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends Applet implements KeyListener, Runnable {
Image bground;
Random generator = new Random();
int r1;
int wall1x;
int wall1y;
int wall1long;
int wall2x;
int wall2y;
int wall2long;
Timer timer;
private Image i;
private Graphics doubleG;
int r2;
int blok_x1 = 800;
int blok_y1;
int blok_x = 800;
int blok_y = 0;
int blok_x_v = 2;
int ballX = 20;
int ballY = 20;
int dx = 0;
int dyclimb = 1;
int dyrise = 1;
double gravity = 3;
double jumptime = 0;
int FPS = 100;
public int tab[];
public boolean grounded = true, up = false;
boolean OVER = false;
#Override
public void init() {
bground = getImage(getCodeBase(), "12.png");
this.setSize(600, 400);
tab = new int[100];
for (int t = 0; t < 100; t++) {
tab[t] = generator.nextInt(380) + 1;
}
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
ballX -= 10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
ballX += 10;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
ballY -= 10;
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
ballY += 10;
}
}
#Override
public void paint(Graphics g) {
g.drawImage(bground, 0, 0, this);
if (OVER == false) {
for (int i = 0; i < 100; i++) {
g.setColor(Color.green);
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
g.fillRect(wall1x, wall1y, 20, wall1long);
g.setColor(Color.green);
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
g.fillRect(wall2x, wall2y, 20, wall2long);
g.setColor(Color.green);
}
g.setColor(Color.red);
g.fillOval(ballX, ballY, 20, 20);
} else {
g.drawString("GAME OVER", 300, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
g.setColor(Color.green);
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
g.setColor(Color.green);
}
doubleG.setColor(getBackground());
g.setColor(Color.green);
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
g.setColor(Color.green);
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void run() {
int time = 10;
while (true) {
if (up == true) {
ballY -= dyclimb;
time--;
} else {
ballY += dyrise;
}
if (time == 0) {
time = 10;
up = false;
}
blok_x--;
blok_x1--;
if (ballX > 600 || ballX < 0 || ballY > 400 || ballY < 0) {
OVER = true;
}
for (int i = 0; i < 100; i++) { // collision algorithm
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
if (ballX + 20 >= wall1x && ballX <= wall1x + 20 && ballY <= wall1y + wall1long && ballY >= wall1x - 20) { //wall1
OVER = true;
}
}
for (int i = 0; i < 100; i++) {
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
if (ballX + 20 >= wall2x && ballX <= wall2x + 20 && ballY <= wall2y + wall2long && ballY >= wall2x - 20) { //wall2
OVER = true;
}
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()

Categories

Resources