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);
}
}
Related
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);
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class snakeGame extends Applet implements Runnable, KeyListener{
private snake snk = new snake();
private Thread thread;
private Graphics gfx;
private Image img;
private boolean game = true;
public void init(){
setBackground(Color.black);
this.setSize(new Dimension(800,800));
this.addKeyListener(this);
img = createImage(800, 800);
gfx = img.getGraphics();
thread = new Thread();
thread.start();
}
public void paint(Graphics g){
//g.setColor(Color.white);
//g.fillRect(snk.getX(), snk.getY(), 10, 10);
snk.draw(g);
}
public void update(Graphics g){
paint(g);
}
public void repaint(Graphics g){
paint(g);
}
public void run(){
while(game){
//snk.move();
if(snk.getDiry() == -1){
snk.y -= 10;
}
if(snk.getDiry() == 1){
snk.y += 10;
}
if(snk.getDirx() == -1){
snk.x -= 10;
}
if(snk.getDirx() == 1){
snk.x += 10;
}
repaint();
try{
Thread.sleep(200);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_UP){
snk.setDirx(0);
snk.setDiry(-1);
System.out.println("UP");
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN){
snk.setDirx(0);
snk.setDiry(1);
System.out.println("DOWN");
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT){
snk.setDirx(-1);
snk.setDiry(0);
System.out.println("LEFT");
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
snk.setDirx(1);
snk.setDiry(0);
System.out.println("RIGHT");
}
else{
System.out.println("Wrong key pressed");
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
This is the code for the snakeGame class. There is one other file named "snake.java" which contains accessors and mutators for the variables and defination of draw function. This is the snake.java
import java.awt.*;
public class snake {
public int x, y;
private int dirx, diry;
public snake(){
this.x = 400;
this.y = 400;
this.dirx = 0;
this.diry = 1;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.fillRect(getX(), getY(), 20, 20);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getDirx(){
return dirx;
}
public int getDiry(){
return diry;
}
public void setDirx(int dirx){
this.dirx = dirx;
}
public void setDiry(int diry){
this.diry = diry;
}
}
The snake won't show up in the applet window. Please help me see what is wrong in the code and how it can be made better. I am new with coding and StackOverflow so please forgive me if I have made some stupid mistake.
Thanks in advance
PEACE
I'm trying to create a square that can move by pressing keys. When I Compiled & Ran the code it wouldn't move. So I began debugging (as well as I'm capable of). The problem seems to be that the run() function isn't being called. Why is this ? My understanding was that when using the interface Runnable, the run method is called automatically. I posted all the code in action.
Why isn't run() being called automatically and how can I change my program so it will call ?
Game.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel implements Runnable{
private static final int WIDTH = 800, HEIGHT = WIDTH / 12 * 9; //Widescreen
private Thread game_thread;
private boolean running = false;
public int x_speed = 0, y_speed = 0;
public Square square;
public Game(){
game_thread = new Thread("GameThread");
square = new Square(this);
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_A){
x_speed = -1;
}
if(e.getKeyCode() == e.VK_D){
x_speed = 1;
}
if(e.getKeyCode() == e.VK_S){
y_speed = -1;
}
if(e.getKeyCode() == e.VK_W){
y_speed = 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
});
}
public void start(){
System.out.println("Started");
game_thread.start();
running = true;
System.out.println(running);
}
public void stop(){
try{
running = false;
game_thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
square.render(g2d);
}
public void update(){
square.move();
System.out.println(x_speed + ", " + y_speed);
}
public void run(){
System.out.println("run method started");
while(running){
System.out.println("Running");
//Update screen info
update();
//Re-render
repaint();
try{
game_thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String args[]){
JFrame frame = new JFrame("Moving Thangs");
Game game = new Game();
frame.setSize(game.WIDTH, game.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.setVisible(true);
game.start();
}
}
Square.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Square {
public static final int s_WIDTH = 80, s_HEIGHT = s_WIDTH;
public int x, y;
private Game game;
public Square(Game game){
x = 50;
y = 50;
this.game = game;
}
public void move(){
if(x >= 0 && x <= game.getWidth() - s_WIDTH){
x += game.x_speed;
}
if(y >= 0 && y <= game.getHeight() - s_HEIGHT){
y += game.y_speed;
}
}
public void render(Graphics2D g2d){
g2d.setColor(Color.ORANGE);
g2d.fillRect(x, y, s_WIDTH, s_HEIGHT);
}
}
When you create the thread using new Thread("GameThread") you don't pass this as a runnable to the thread. You need to pass it as the first argument in the constructor like new Thread(this, "GameThread") and then everything should work.
I have a very strange problem.
I am making a simple 2d platformer using Java.
The collision detection with the player and a platform, doesn't work.
But the strange thing is, when I print something to the screen to see if the collision if-statement is executed, the collision works o_O
Maybe it's a bit confusing, please see my code.
The Main class(which is good I think):
import javax.swing.*;
public class Main extends JFrame{
private static final long serialVersionUID = 1L;
GameClass gc = new GameClass();
public Main(){
setSize(gc.WIDTH,gc.HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Flying GoatZ!");
add(new GameClass());
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
GameClass class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class GameClass extends JPanel implements ActionListener, KeyListener, MouseListener{
//OBJECTS
Text text = new Text();
openImages open_img = new openImages();
Random ran = new Random();
//VARIABLES
static final long serialVersionUID = 1L;
final int WIDTH = 800;
final int HEIGHT = 600;
int goatx = WIDTH/2;
int goaty = 350;
int goatspeed = 0;
int fallspeed = 15;
int maxy = 150;
boolean up = false;
boolean flying = true;
ArrayList<Integer> xes = new ArrayList<Integer>();
ArrayList<Integer> yes = new ArrayList<Integer>();
//FPS SETTER AND KEYLISTENERS
public GameClass(){
Timer time = new Timer(15, this);
time.start();
this.addKeyListener(this);
this.setFocusable(true);
open_img.openImage();
}
public void update(){
Collision();
goatx += goatspeed;
if(up){
if(goaty > maxy){
goaty -= 5;
}else{
up = false;
}
}else
if(goaty < 350)
goaty += fallspeed;
}
public void print(String msg){
System.out.println(msg);
}
public void platformDrawing(Graphics g,int x,int y,int x1,int y1, int x2, int y2){
g.setColor(Color.RED);
g.drawImage(open_img.block,x, y, null);
g.drawImage(open_img.block,x1, y1, null);
g.drawImage(open_img.block,x2, y2, null);
xes.addAll(Arrays.asList(x,x1,x2));
yes.addAll(Arrays.asList(y,y1,y2));
}
//HERE IS THE COLLISION METHOD(I NEED THE PLAYER TO STAND STILL WHEN IT IS ON THE PLATFORM.
public void Collision(){
for(int x : xes){
for(int y : yes){
if( ( (goatx > x-20) && (goatx < (x + 150)) ) && ( (goaty+open_img.goat.getHeight(null)) <= y ) ){
//print("TEST");
fallspeed = 0;
}else{
fallspeed = 10;
}
}
}
}
//ALL TEH DRAWING
public void paintComponent(Graphics g){
//MAP
g.setColor(Color.CYAN);
g.fillRect(0,0,WIDTH,HEIGHT);
g.setColor(Color.ORANGE);
g.fillRect(0, HEIGHT-100, WIDTH, 100);
g.setColor(Color.GREEN);
g.fillRect(0, HEIGHT-125, WIDTH, 25);
//PLAYER & PLATFORMS
platformDrawing(g,50,350,300,350,600,350);
g.drawImage(open_img.goat, goatx, goaty, null);
g.dispose();
}
//THIS IS EXECUTED EVERYTIME
public void actionPerformed(ActionEvent e){
update();
repaint();
}
//KEY DETECTION
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT){
goatspeed = -5;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
goatspeed = 5;
}
if(e.getKeyCode() == KeyEvent.VK_SPACE){
if(flying){
flying = false;
up = true;
}
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT){
goatspeed = 0;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
goatspeed = 0;
}
if(e.getKeyCode() == KeyEvent.VK_SPACE){
flying = true;
}
}
//SOME STUFF THAT YOU HAVE TO IGNORE LEL
public void keyTyped(KeyEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
}
I don't understand why a print statement can make the difference...
Any help is appreaciated, thanks!
Oh, and sorry for bad English or unclear question.
I made a ping pong game in Java but the paddles doesn't work, and I can't figure out the problem.
Main class: in the main class I give the thread and run the program:
package pingpong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class PingPong extends JFrame {
int Gwidth=400,Gheight=300;
Dimension screenSize = new Dimension(Gwidth,Gheight);
//double Buffering
Image dbImage;
Graphics dbg;
//ball objects
static Ball b = new Ball(193,143);
//constructor
public PingPong() {
this.setTitle("ping pong Game");
this.setResizable(false);
this.setSize(screenSize);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBackground(Color.black);
this.setVisible(true);
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
draw(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics g) {
b.draw(g);
b.p1.draw(g);
b.p2.draw(g);
g.setColor(Color.white);
g.drawString(""+b.p1Score,15,50);
g.drawString(""+b.p2Score,370,50);
repaint();
}
//event listining class
public class AL extends KeyAdapter { //key buildings
#Override
public void keyPressed(KeyEvent e) {
b.p1.keyPressed( e);
b.p2.keyPressed( e);
}
public void keyRealesed(KeyEvent e){
b.p1.keyReleased( e);
b.p2.keyReleased( e);
}
}
public static void main(String[] args) {
PingPong pp = new PingPong();
//create and start threads
Thread ball=new Thread(b);
ball.start();
Thread p1=new Thread(b.p1);
Thread p2= new Thread(b.p2);
p1.start();
p2.start();
}
}
this is my ball class:
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
public class Ball implements Runnable{
//global variables
int x,y,XDir,YDir;
//score
int p1Score,p2Score;
Paddle p1=new Paddle(15 , 140, 1);
Paddle p2=new Paddle(370, 140 ,2 );
Rectangle ball;
public Ball(int x,int y){
p1Score=p2Score=0;
this.x=x;
this.y=y;
//randomly moving the ball
Random r=new Random();
int rDir = r.nextInt(1);
if (rDir == 0) {
rDir--;
}setXDir(rDir);
int yrDir = r.nextInt(1);
if (yrDir == 0) {
yrDir--;
}setYDir(yrDir);
//create 'ball'
ball = new Rectangle(this.x, this.y,7, 7);
}
public void collision(){
if(ball.intersects(p1.paddle)){
setXDir(+1);}
if(ball.intersects(p2.paddle)){
setXDir(-1);}
}
public void draw(Graphics g){
g.setColor(Color.cyan);
g.fillRect(ball.x,ball.y,ball.width,ball.height);
}
public void move(){
collision();
ball.x +=XDir;
ball.y +=YDir;
//bounce the ball when edge is detected
if(ball.x<0){
setXDir(+1);
//add to score
p1Score++; //?
}
if(ball.x>=385){
setXDir(-1);
//add to score
p2Score++; //?
}
if(ball.y<=15)
setYDir(+1);
if(ball.y>=270)
setYDir(-1);
}
public void setXDir(int xdir){
XDir=xdir;
}
public void setYDir(int ydir){
YDir=ydir;
}
public void run(){
try{
while(true){
move();
Thread.sleep(4);
}
}catch(Exception e) {System.out.println("sorry"+e.getMessage());}
}
}
and there is my paddle class :
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Paddle implements Runnable {
int x, y, yDir, id;
Rectangle paddle;
public Paddle(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
paddle = new Rectangle(x, y, 15, 50);
}
public void keyPressed(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(+1);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(+1);
}
break;
}
}
public void keyReleased(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(0);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(0);
}
break;
}
}
public void draw(Graphics g) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 2:
g.setColor(Color.YELLOW);
//draw paddle #1
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
case 1:
g.setColor(Color.white);
// draw paddle #2
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
}
}
public void setYDir(int ydir) {
yDir = ydir;
}
public void move() {
paddle.x += yDir;
if (paddle.y <= 15) {
paddle.y = 15;
}
if (paddle.y >= 250) {
paddle.y = 250;
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(6);
}
} catch (Exception e) {
System.out.println("try again" + e.getMessage());
}
}
}
I personally think I have a problem in the paddle but I can't figure it out.
If you're moving your paddle in Y axis (inside move, this looks wrong:
paddle.x += yDir;
Should be
paddle.y += yDir;