2D Pac-Man getting Pac Man to move - java

I am trying to create a 2D Pac-Man game using Java but I'm having trouble getting the rectangle which will represent the Pac-Man to move. I think that my issue might be somewhere in my keyPressed method in the Game class but I'm not sure. This is what I have in my main class so far.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable,KeyListener {
private static final long serialVersionUID = 1L;
private boolean isRunning = false;
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public static final String TITLE = "Pac-Man";
public Thread thread;
public static Player player;
public Game() {
Dimension dimension = new Dimension(Game.WIDTH,Game.HEIGHT);
setPreferredSize(dimension);
setMinimumSize(dimension);
setMaximumSize(dimension);
addKeyListener(this);
player = new Player(Game.WIDTH/2,Game.HEIGHT/2);
}
public synchronized void start() {
if(isRunning) {
return;
} else {
isRunning = true;
thread = new Thread(this);
thread.start();
}
}
public synchronized void stop() {
if(!isRunning) {
return;
} else {
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void tick() {
player.tick();
}
private void render() {
BufferStrategy bs= getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
player.render(g);
g.dispose();
bs.show();
}
#Override
public void run() {
int fps = 0;
double timer = System.currentTimeMillis();
long lastTime = System.nanoTime();
double targetTicks = 60.0;
double delta = 0;
double ns = 1000000000/targetTicks;
while(isRunning) {
long currentTime = System.nanoTime();
delta += (currentTime - lastTime)/ns;
lastTime = currentTime;
while(delta >= 1) {
tick();
render();
fps++;
delta--;
}
if((System.currentTimeMillis() - timer) >= 1000) {
System.out.println(fps);
fps = 0;
timer += 1000;
}
}
stop();
}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setTitle(Game.TITLE);
frame.add(game);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = true;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = true;
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
player.up = true;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
player.down = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = false;
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
player.up = false;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
player.down = false;
}
}
}
This is what I have in the Player class so far.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Player extends Rectangle{
private static final long serialVersionUID = 1L;
public boolean right;
public boolean left;
public boolean up;
public boolean down;
private int speed = 4;
public Player(int x, int y) {
setBounds(x,y,32,32);
}
public void tick() {
if(right) {
x+=speed;
}
if(left) {
x-=speed;
}
if(up) {
y-=speed;
}
if(down) {
y+=speed;
}
}
public void render(Graphics g) {
g.setColor(Color.yellow);
g.fillRect(x,y,width,height);
}
}

Related

My Rectangle moves up despite what key I press with key Listener in Java

I am generally a very bad programmer but have been trying to learn game development for a school project. My problem is that I have a draw method that draws a white rectangle and have a key Listener for movement but for some reason it moves upward despite what key I press not just W A S and D.
If you could help with this I would appreciate.
thanks
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
final int screenHeight = 600;
final int screenWidth = 800;
final int playerSize = 48;
int fps = 60;
KeyHandler keyH = new KeyHandler();
Thread gameThread;
//player default position
int playerX = 100;
int playerY = 100;
int playerSpeed = 1;
public GamePanel() {
this.setPreferredSize(new Dimension (screenWidth, screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
this.addKeyListener(keyH);
this.setFocusable(true);
}
public void startGameThread() {
gameThread = new Thread (this);
gameThread.start();
}
public void run() {
double drawInterval = 1000000000/fps; // 0.01666 seconds = 60 times per seconds
double nextDrawTime = System.nanoTime() + drawInterval;
while(gameThread != null) {
System.out.println("this gmae is runing");
// update information such as character positions
// draw the screen with the updated information
update();
repaint();
try {
double remainingTime = nextDrawTime - System.nanoTime();
remainingTime = remainingTime/1000000;
if(remainingTime<0) {
remainingTime = 0;
}
Thread.sleep ((long) remainingTime);
nextDrawTime += drawInterval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void update() {
if(keyH.upPressed ==true) {
playerY = playerY - playerSpeed;
}
else if (keyH.downPressed ==true){
playerY = playerY + playerSpeed;
}
else if (keyH.leftPressed== true){
playerX = playerX - playerSpeed;
}
else if (keyH.rightPressed == true) {
playerX = playerX +playerSpeed;
}
}
public void paintComponent(Graphics g) {
// to draw something
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
g2.fillRect(playerX, playerY, playerSize, playerSize);
g2.dispose();
}
}
package game;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener {
public boolean leftPressed;
public boolean rightPressed;
public boolean upPressed;
public boolean downPressed;
public boolean spacePressed;
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_D);{
rightPressed = true;
}
if(code == KeyEvent.VK_A);{
leftPressed = true;
}
if(code == KeyEvent.VK_W);{
upPressed = true;
}
if(code == KeyEvent.VK_S);{
downPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
int code = e.getExtendedKeyCode();
if(code == KeyEvent.VK_D);{
rightPressed = false;
}
if(code == KeyEvent.VK_A);{
leftPressed = false;
}
if(code == KeyEvent.VK_W);{
upPressed = false;
}
if(code == KeyEvent.VK_S);{
downPressed = false;
}
}
}

Java Pong Game, Paddle is not moving [duplicate]

This question already has answers here:
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 5 years ago.
When VK_UP or VK_DOWN is pressed the Graphic g I created is not changing its position whatsoever. If someone could look and see if there is something wrong with my move method etc. Would really appreciate it.
Here is all my code so far:
package ping2;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ping2 extends Applet implements Runnable, KeyListener{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
UserPaddle user1;
public void init() {
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
user1 = new UserPaddle(1);
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
user1.draw(g);
}
public void update(Graphics g) {
paint(g);
}
public void run() {
for(;;) {
user1.move();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(true);
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(false);
}
}
public void keyTyped(KeyEvent arg0) {
}
}
package ping2;
import java.awt.*;
public class UserPaddle implements InterfaceBar{
double y, yVelocity;
boolean upAccel, downAccel;
int player1, x;
final double FRICTION = 0.90;
public UserPaddle(int player1) {
upAccel = false;
downAccel = false;
y = 210;
yVelocity = 0;
if(player1 == 1)
x = 20;
else
x = 660;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int)y, 20, 80);
}
public void move() {
if(upAccel) {
yVelocity -= 2;
}else if(downAccel) {
yVelocity += 2;
}
//Automatically slows bar down if key not being pressed.
else if(!upAccel && !downAccel) {
yVelocity *= FRICTION;
}
}
public void setUpAccel(boolean input) {
upAccel = input;
}
public void setDownAccel(boolean input) {
downAccel = input;
}
public int getY() {
return (int)y;
}
}
package ping2;
import java.awt.Graphics;
public interface InterfaceBar {
public void draw(Graphics g);
public void move();
public int getY();
}
I have modified your move() a bit give it a try
move()
public void move() {
if(upAccel) {
yVelocity -= 2;
y = yVelocity;
}else if(downAccel) {
yVelocity += 2;
y = yVelocity;
}
}

JAVA: Program not detecting key presses using KeyListener

I'm making a space shooter game in Java. I have it set to move up when I press the up key, but it is currently not working at all. I am using the KeyPressed method in the KeyListener interface. Here is my code. It is in 2 classes.
Game.java
package main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Space Shooter";
private boolean running = false;
private Thread thread;
private Player player;
private BufferedImage playerImage;
int playerx;
int playery;
public Game() {
player = new Player((WIDTH/2)-32, 400);
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("/res/player.png"));
} catch (IOException e) {
e.printStackTrace();
}
addKeyListener(this);
}
private synchronized void start() {
if (running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop() {
if (!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
#Override
public void run() {
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta > 1) {
tick();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " TICKS, " + frames + " FPS");
updates = 0;
frames = 0;
}
}
stop();
}
public void tick() {
playerx = player.getX();
playery = player.getY();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(playerImage, playerx, playery, this);
g.dispose();
bs.show();
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
player.setY(playery -= 5);
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
game.start();
}
}
Player.java
package main;
public class Player {
int x, y;
public Player(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
When you click on the game and then press the keys does it work?
If so all you need to do is call
setFocusable(true);
requestFocus();
then it should work

paintComponent method won't work - Java

When I use this code my screen will be empty. So that means
something is wrong with my paintComponent method. But what is wrong? And how do I fix it? My expected output was a dark gray rectangle, and an image.
Code:
package _47b3n.seg.main.engine;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import _47b3n.seg.main.frame.Frame;
public class Engine extends JPanel {
public int xOff;
public int yOff;
public int x;
public int y;
public int fpsInt = 199;
public boolean isRunning = true;
public FPS fps = new FPS();
public static void main(String [] args) {
Frame frame = new Frame();
frame.setFrame(800, 600, "Super easy game", "0.0.1");
new Engine();
}
public Engine() {
start();
}
public void move() {
x+=xOff;
y+=yOff;
}
public void start() {
Thread loop = new Thread () {
public void run() {
gameLoop();
addKeyListener(new keyInput());
}
};
loop.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(10, 10, 10, 10);
g.drawImage(new ImageIcon("Poppetje.jpg").getImage(), x, y, null);
}
public void gameLoop() {
while(isRunning) {
move();
repaint();
fps.update();
fpsInt++;
if (fpsInt == 200) {
System.out.println("[Console] " + fps.getFPS() + " FPS");
fpsInt = 0;
}
try {Thread.sleep(17);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public class keyInput extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W) {
yOff = -1;
}
if (key == KeyEvent.VK_S) {
yOff = 1;
}
if (key == KeyEvent.VK_A) {
yOff = -1;
}
if (key == KeyEvent.VK_D) {
xOff = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yOff = 0;
}
if (key == KeyEvent.VK_S) {
yOff = 0;
}
if (key == KeyEvent.VK_A) {
xOff = 0;
}
if (key == KeyEvent.VK_D) {
xOff = 0;
}
}
}
}
Thanks
Don't know if it is the only problem, but you never add the panel to the frame:
//new Engine();
Engine engine = new Engine();
frame.add(engine);
frame.setVisible(true);

Rectangle.y issue, persistently rendering at 0

I'm trying to render a rectangle to a JPanel:
playerRect = new Rectangle(100,100,10,10);
Problem is, playerRect renders at 100,0 every time. I've updated Eclipse and Java, as well as troubleshoot my code and played with the x, y, width, height (although I'm not sure how my code could affect java.awt.Rectangle).
Any clue as to what is causing this?
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
public class Player {
private World world;
private Rectangle playerRect;
private Image playerImg;
protected int xDirection, yDirection;
//block variables
private int hoverX, hoverY;
private boolean hovering;
public Player(World world){
this.world = world;
playerImg = new ImageIcon("D:/Student Data/gametest1/GameEngine/res/player.png").getImage();
playerRect = new Rectangle(100, 100, 10, 10); // ### here's the issue ###
}
private void setXDirection(int d){
xDirection = d;
}
private void setYDirection(int d){
yDirection = d;
}
public void update(){
move();
checkForCollision();
}
private void move(){
playerRect.x += xDirection;
playerRect.y =+ yDirection;
}
private void checkForCollision(){
}
//Drawing methods
public void draw(Graphics g){
g.drawImage(playerImg, playerRect.x, playerRect.y, null);
}
private void drawBlackOutline(Graphics g){
g.setColor(Color.BLACK);
g.drawRect(hoverX,hoverY, world.blocks[0].width, world.blocks[0].height);
if(hovering){drawBlackOutline(g);}
}
//mouse events
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
public void mouseMoved(MouseEvent e){
int x = e.getX();
int y = e.getY();
int px = playerRect.x;
int py = playerRect.y;
for(int i =0; i <world.arrayNum; i++){
if(world.blocks[i].contains(x,y)){
hovering = true;
hoverX = world.blocks[i].x;
hoverY = world.blocks[i].y;
break;
}else{hovering = false;}
}
}
public void mouseDragged(MouseEvent e){
}
private class Weapon{
public static final int UNARMED = 0;
public static final int PICKAXE = 1;
public static final int GUN = 2;
public int CURRENT_WEAPON;
public Weapon( int w){
switch(w){
default:
System.out.println("no weapon sellected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
break;
case GUN:
CURRENT_WEAPON = GUN;
break;
}
}
public void selectWeapon( int w){
switch(w){
default:
System.out.println("no weapon sellected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
break;
case GUN:
CURRENT_WEAPON = GUN;
break;
}
}
public boolean isEquipped(int w){
if(w == CURRENT_WEAPON){
return true;
}
else
return false;
}
}
}
Here's where the rectangle is drawn to the JPanel:
package game;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
//Double Buffering
private Image dbImage;
private Graphics dbg;
//JPanel variables
static final int GWIDTH = 900, GHEIGHT = 600;
static final Dimension gameDim = new Dimension(GWIDTH, GHEIGHT);
//Game variables
private Thread game;
private volatile boolean running = false;
public int tickCount = 0;
private static final int DELAYS_BEFORE_YIELD = 10;
private long period = 6*1000000; //ms --> nano
//Game Objects
World world;
Player p1;
public GamePanel(){
world = new World();
p1 = new Player(world);
setPreferredSize(gameDim);
setBackground(Color.WHITE);
setFocusable(true);
requestFocus();
//Handle all key inputs from user
addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_W){
world.navigateMap(World.PAN_UP);}
if(e.getKeyCode() == KeyEvent.VK_S){
world.navigateMap(World.PAN_DOWN);}
if(e.getKeyCode() == KeyEvent.VK_A){
world.navigateMap(World.PAN_LEFT);}
if(e.getKeyCode() == KeyEvent.VK_D){
world.navigateMap(World.PAN_RIGHT);}
}
#Override
public void keyReleased(KeyEvent e){
world.stopMoveMap();
}
#Override
public void keyTyped(KeyEvent e){
}
});
addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
}
#Override
public void mouseReleased(MouseEvent e){
}
#Override
public void mouseClicked(MouseEvent e){
}
});
addMouseMotionListener(new MouseAdapter(){
#Override
public void mouseMoved(MouseEvent e){
p1.mouseMoved(e);
}
#Override
public void mouseDragged(MouseEvent e){
}
#Override
public void mouseEntered(MouseEvent e){
}
#Override
public void mouseExited(MouseEvent e){
}
});
}
private void startGame(){
if(game == null || !running){
game = new Thread(this);
game.start();
running = true;
}
}
public void addNotify(){
super.addNotify();
startGame();
}
public void stopGame(){
if(running){
running = false;
}
}
public void run() {
long lastTime = System.nanoTime();
long beforeTime, afterTime, diff, sleepTime, overSleepTime = 0;
int delays = 0;
while(running){
beforeTime =System.nanoTime();
gameUpdate();
gameRender();
paintScreen();
afterTime = System.nanoTime();
diff = afterTime - beforeTime;
sleepTime = (period - diff) - overSleepTime;
//if the sleep time is between 0 and the period, sleep
if(sleepTime < period && sleepTime > 0){
try {
game.sleep(sleepTime/1000000L);
overSleepTime = 0;
} catch (InterruptedException e) {
System.err.println("You done goofed!");
}
}
//the difference was greater than the period
else if(diff>period){
overSleepTime = diff - period;
}
//accumulate the amount of delays, and eventually yield
else if(++delays >= DELAYS_BEFORE_YIELD){
game.yield();
}
//the loop took less time than expected,but we need to make up for oversleep time
else{overSleepTime = 0;}}
}
private void gameUpdate(){
if(running && game != null){
//update game state
world.moveMap();
p1.update();
}
}
private void gameRender(){
if(dbImage == null){ //create the buffer
dbImage = createImage(GWIDTH, GHEIGHT);
if(dbImage == null){
System.err.println("dbImage is still null!");
return;
}else{
dbg = dbImage.getGraphics();
}
}
//Clear the screen
dbg.setColor(Color.BLACK);
dbg.fillRect(0, 0, GWIDTH, GHEIGHT);
//Draw Game elements
draw(dbg);
}
//##### Draw all game content in this method #####//
public void draw(Graphics g){
world.draw(g);
p1.draw(g);
//g.setColor(Color.RED);
//g.setFont(new Font("PR Celtic Narrow", Font.BOLD, 50));
//String str = "MentalBrink Lv. 5";
//g.drawString(str, 100,100);
}
private void paintScreen(){
Graphics g;
try{
g = this.getGraphics();
if(dbImage != null && g != null){
g.drawImage(dbImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync(); //for Linux people.
g.dispose();
}catch(Exception e){
System.err.println(e);
}
}
private void log(String s){
System.out.println(s);
}
}

Categories