Trying to update a boolean from a class in another class D: - java

First of all, sorry for my english!
I have a problem, I´m trying to make a simple java videogame, and I make booleans for the inputs. The inputs works well, but when I try to update the booleans in another class, it doesnt work.
I put here the important classes
I put all the classes in this drive.
Classes
package Launcher;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener {
public boolean upPressed, downPressed, leftPressed, rightPressed;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_W){
upPressed = true;
System.out.println(upPressed);
}
if(code == KeyEvent.VK_S){
downPressed = false;
}
if(code == KeyEvent.VK_A){
leftPressed = true;
}
if(code == KeyEvent.VK_D){
rightPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_W){
upPressed = false;
}
if(code == KeyEvent.VK_S){
downPressed = false;
}
if(code == KeyEvent.VK_A){
leftPressed = false;
}
if(code == KeyEvent.VK_D){
rightPressed = false;
}
}
}
package Launcher;
import java.awt.*;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
//Window settings variables
KeyHandler KH = new KeyHandler();
final int originalTileSize = 16; //16x16px
final int scale = 3;
final int tileSize = originalTileSize * scale; //48x48px
final int maxScreenCol = 16; //Tiles in a column
final int maxScreenRow = 12; //Tiles in a row
final int maxScreenWidth = tileSize * maxScreenCol;
final int maxScreenHeight = tileSize * maxScreenRow;
Thread gameThread;
//Player pos
int playerX = 100;
int playerY = 100;
int playerSpeed = 4;
public GamePanel(){
//Window Settings with variable implementation
this.setPreferredSize(new Dimension(maxScreenWidth, maxScreenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
this.addKeyListener(KH);
this.setFocusable(true);
}
public void startGameThread(){
gameThread = new Thread(this);
gameThread.start();
}
public void update(){
//System.out.println(playerY);
boolean upP = KH.upPressed;
//System.out.println(upP);
if(upP){
System.out.println("Updating");
playerY -= playerSpeed;
}
else if(KH.downPressed == true){
playerY += playerSpeed;
}
else if(KH.leftPressed == true){
playerX -= playerSpeed;
}
else if(KH.rightPressed){
playerX += playerSpeed;
}
}
public void run(){
while(gameThread != null){
//System.out.println("Running game");
//1.Update
update();
//2Draw screen info
repaint();
}
}
I only want the update function get the boolean variables, for me to be able to move my character. Thank you so much!

I had a look at the other classes and the reason is outside the code above, it's in class Launcher.Main:
public static void main(String[] args){
WindowPanel WP = new WindowPanel();
WP.windowPanel();
GamePanel GP = new GamePanel();
GP.startGameThread();
}
in here you create a new instance of class WindowPanel, which - by itself - create a another instance of GamePanel.
public void windowPanel(){
// ...
GamePanel gamePanel = new GamePanel();
window.add(gamePanel);
window.pack();
// ...
}
So, the GamePanel that you created in Main, after you created the WindowPanel is not related to the GamePanel you create afterwards and start threading.
Fix:
remove the additional GamePanel from Main class
add to the end of windowPanel() method in WindowPanel class:
gamePanel.startGameThread();

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;
}
}
}

Dr Java- Static Error: This class does not have a static void main method accepting String[]

I try running this program and I get a static void error. I am new to this and I have no idea how to fix this problem so any input would be helpful, thank you!
package johnbarthelmes.Java;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image apple;
private Image head;
public Board() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("head.png");
head = iih.getImage();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * 10;
y[z] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= B_HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= B_WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if(!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
#Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}
If it helps at all this is the code for the snake game that I got from a Dr Java tutorial in which I followed all the steps correctly as far as I know. There was no errors compiling but when I ran the program I got that error message.
In order to run an application, your class needs a main method with a certain signature, so Java knows what to do. Probably you want to start up the program by showing your JFrame:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Board b = new Board();
b.setVisible(true);
}
});
}
You need to add a main method. It's the entry point to every Java application. It looks like it should have this implementation, based on your code sample.
public static void main(String[] args) {
Board board = new Board();
// need to do something else with board here maybe?
}

Java 2d Game-Very strange "bug" in game

I have a very strange bug in my 2d game made using Java.
Description of the game: the player can move a rocket sprite with the mouse, and must dodge a rectangle that is going to follow the player and kill the player(by collision). Instead of following the player, it only moves to the beginning coordinates of the player, which is 400,400. It should move to the direction the player goes to. Please help me if you know what is wrong.
Main class:
import javax.swing.*;
public class Main extends JFrame{
private static final long serialVersionUID = 1L;
final static int WW = 800;
final static int WH = 600;
public Main(){
setSize(WW,WH);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Space Game");
add(new GameClass());
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
GameClass class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GameClass extends JPanel implements ActionListener, KeyListener{
private static final long serialVersionUID = 1L;
Enemy enemy = new Enemy();
Player player = new Player();
public GameClass(){
Timer time = new Timer(15, this);
time.start();
this.addKeyListener(this);
this.setFocusable(true);
player.openImage();
}
public void update(){
player.update();
enemy.update();
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0,0,Main.WW,Main.WH);
player.paint(g);
enemy.paint(g);
g.dispose();
}
public void actionPerformed(ActionEvent e){
update();
repaint();
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT){
player.setSpeed(-5);
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
player.setSpeed(5);
}
else if(e.getKeyCode() == KeyEvent.VK_UP){
player.setFly(-5);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
player.setFly(5);
Player.goDown = true;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT){
player.setSpeed(0);
}
if(e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN){
player.setFly(0);
Player.goDown = false;
}
}
public void keyTyped(KeyEvent e){
}
}
Enemy class:
import java.awt.*;
public class Enemy {
private int x = -100;
private int y = -100;
Player player = new Player();
public void update(){
System.out.println(player.getX());
if(player.getX() < this.x){
this.x -= 5;
}
if(player.getX() > this.x){
this.x += 5;
}
if(player.getY() > this.y){
this.y += 5;
}
if(player.getY() < this.y){
this.y -= 5;
}
}
public void paint(Graphics g){
g.setColor(Color.ORANGE);
g.fillRect(x, y, 50, 50);
}
}
Player class:
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.*;
public class Player {
private Image image;
private int player_x = Main.WW/2;
private int player_xspeed = 0;
private int player_y = Main.WH/2;
private int player_yspeed = 0;
private int flamey = player_y + 100;
private int flamex;
private int newx;
private int newy;
static boolean goDown = false;
public Player(){
newx = player_x;
newy = player_x;
}
public void openImage(){
try {
image = ImageIO.read(new File("spaceship.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g){
flamex = player_x + 20;
g.drawImage(image,player_x,player_y,null);
g.setColor(Color.YELLOW);
g.fillRect(flamex, flamey+5, 6, 6);
g.fillRect(flamex+10, flamey, 6, 6);
g.fillRect(flamex+10, flamey+15, 6, 6);
g.fillRect(flamex+20, flamey+5, 6, 6);
}
public void update(){
player_x += player_xspeed;
player_y += player_yspeed;
if(flamey < (player_y + 125)){
if(goDown == false)
flamey += 5;
else
flamey += 10;
}else
flamey = player_y + 100;
newx = player_x;
newy = player_y;
}
public void setSpeed(int speed){
player_xspeed = speed;
}
public void setFly(int speed){
player_yspeed = speed;
}
public int getX(){
return newx;
}
public int getY(){
return newy;
}
}
Sorry for bad English, please help me.
Any help appreaciated :)
It's because the Player it follows is created inside Enemy via the line:
public class Enemy {
//...
Player player = new Player();
//...
}
so it's a different player instance to the one you are controlling, which is created in GameClass via:
public class GameClass extends JPanel implements ActionListener, KeyListener{
Enemy enemy = new Enemy();
Player player = new Player();
//...
}
You need to inject the controlled player instance either as a constructor parameter on Enemy, e.g.
public class GameClass extends JPanel implements ActionListener, KeyListener{
Player player = new Player();
Enemy enemy = new Enemy(player);
//...
}
public class Enemy {
//...
Player player;
public Enemy(Player player) { this.player = player; }
//...
}
or via a setter.

Java Game Sprite Stuck

I am having a problem with a stuck sprite as soon as I switch to another JPanel via CardLayout.
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame implements Runnable {
private viewA v1;
private viewB v2;
private viewC v3;
private viewD v4;
private Player player;
private CardLayout c1;
private JPanel contPanel;
// ############## VIEW A BUTTONLISTENER
public class ViewAButtonList implements ActionListener{
public void actionPerformed(ActionEvent ev){
try{
c1.show(contPanel, "1");
} catch (Exception ex){
ex.printStackTrace();
}
}
}
// ############## VIEW B BUTTON LISTENER
public class ViewBButtonList implements ActionListener{
public void actionPerformed(ActionEvent ev){
try{
c1.show(contPanel, "2");
} catch (Exception ex){
ex.printStackTrace();
}
}
}
// ############## VIEWC BUTTON ACTIONEVENT
public class ViewCButtonList implements ActionListener{
public void actionPerformed(ActionEvent ev){
try{
c1.show(contPanel, "3");
} catch (Exception ex){
ex.printStackTrace();
}
}
}
// ############## VIEW D BUTTON ACTION EVENT
public class ViewDButtonList implements ActionListener{
public void actionPerformed(ActionEvent ev){
try{
c1.show(contPanel, "4");
} catch (Exception ex){
ex.printStackTrace();
}
}
}
public Game() {
player = new Player();
// load player settings from server
// ..
// contPanel = new JPanel();
//load views v1 = new ViewA(Player); v2=new ViewB(Player); v3 = new ViewC(Player); v4 =new ViewD(Player);
c1 = new CardLayout();
contPanel.setLayout(c1);
contPanel.add(v1,"1");
contPanel.add(v2,"2");
contPanel.add(v3"3");
contPanel.add(v4,"4");
c1.show(contPanel, "2");
currPos =2;
this.add(contPanel);
setSize(652, 480);
setLocationRelativeTo(null);
setTitle("GAME");
setResizable(false);
setVisible(true);//go to end of view B (x=0), change to View A, close view B
// Create 4 of each button to place in each seperate view (to swtich back and forth)
// ................
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Game();
}
});
}
#Override public void run() { // TODO Auto-generated method stub
} }
Now.. everything works from the standpoint of switching between screens.. but my Player sprite gets stuck on screen after switch, but on initial load I can move the sprite around with the arrow keys. I am not sure if passing the Player on the new ViewA(Player) might be the culprit.. but I have a feeling that it is.. can't figure out what I am doing wrong..
Here's theplayer:
import java.awt.Image; import java.awt.Rectangle; import
java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player {
private String playersprite = "playersprite.png";
private int dx;
private int dy;
private int x;
private int y;
private int width;
private int height;
private boolean isFired;
private boolean visible;
private Image image;
private ArrayList missiles;
public Player() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(playersprite));
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
missiles = new ArrayList();
visible = true;
isFired=false;
//default spawn location
x = 600;
y = 400;
}
public void move() {
x += dx;
y += dy;
if(x<=0){x=0;} if(x>=640-20){x=640-20;} if(y<=0){y=0;}
if(y>=400){y=400;}
}
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;
}
public Image getImage() {
return image;
}
public ArrayList getMissiles() {
return missiles;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isVisible() {
return visible;
}
public Rectangle getBounds() {
return new Rectangle(x, y, 32, 32);
}
public void keyPressed(KeyEvent e) {
System.out.println("X: "+x+",Y: "+y);
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
if(isFired==false){
isFired=true;
fire();
} else return;
}
if (key == KeyEvent.VK_LEFT) {
dx = -2;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 2;
}
if (key == KeyEvent.VK_UP) {
dy = -2;
}
if (key == KeyEvent.VK_DOWN) {
dy = 2;
}
}
public void fire() {
System.out.println("Player used weapon");
// missiles.add(new Missile(x, y));
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
if (key == KeyEvent.VK_SPACE) {
isFired=false;
}
} }
KeyListener require that the component they are registered are focusable AND have focus, this means that when you click something like a JButton focus moves to the button and the component with a KeyListener no longer has keyboard focus and therefore will no longer receive key events.
Instead, it is recommended that you use Key Bindings as this API has the capacity to overcome these limitations

Java pong can't move both paddles at once

Trying to make pong in java but can't move both paddles at once. You can move one or the other but not both at the same time. Do I need to create 2 threads with 2 different pannels?
Here is where I am specifying the key events
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_QUOTE || e.getKeyCode() == KeyEvent.VK_SEMICOLON){
if(e.getKeyCode() == KeyEvent.VK_A){
y-=10;
}
if(e.getKeyCode() == KeyEvent.VK_S){
y+=10;
}
if(e.getKeyCode() == KeyEvent.VK_QUOTE){
ytwo-=10;
}
if(e.getKeyCode() == KeyEvent.VK_SEMICOLON){
ytwo+=10;
}
}
}
Here is the full code
import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JFrame implements ActionListener{
//implement constants
PongPanel pongPanel = new PongPanel();
//JFrame pong x and y coordinates
static final int jfpX = 150;
static final int jfpY = 20;
// JFrame pong width and height
static final int jfpW = 800;
static final int jfpH = 600;
Thread thrd;
public static void main(String[] args) {
Pong jfp = new Pong();
jfp.setVisible(true);
}
public Pong(){
setBounds(jfpX,jfpY,jfpW,jfpH);
setTitle("Pong");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(Color.black);
add(pongPanel);
addKeyListener(pongPanel);
thrd = new Thread (pongPanel);
thrd.start();
}
public void actionPerformed(ActionEvent e) {
}
}
class PongPanel extends JPanel implements Runnable, KeyListener{
Random random = new Random();
static final int jpW = 800;
static final int jpH = 600;
int paddleStart = (jpH/2)-35;
int paddleStarttwo = (jpH/2)-35;
int ballStartX = (jpW/2)-20;
int ballStartY = (jpH/2)-20;
int ytwo,x,y;
int ballD = 30;
int paddleW1 = 20;
int paddleH1 = 100;
int paddleW2 = 20;
int paddleH2 = 100;
int min = -2;
int max = 2;
int randomBallx, randomBally;
// int randomBallx = random.nextInt(max-min+1)+min;
// int randomBally = random.nextInt(max-min+1)+min;
int rand1 = random.nextInt(2-1 + 1)+1; // random for function to determine ballx and bally
int rand2 = random.nextInt(2-1+2)+1;
int dx = 4;
int dy = 4; //direction of y
public void ballNotZero(){// makes sure the ball doesnt go straight up and down
if (randomBallx ==0){
randomBallx = random.nextInt(max-min+1)+min;
}
if(randomBally == 0){
randomBally=random.nextInt(max-min+1)+min;
}
// if(rand1 ==1){
// randomBallx=-1;
// }
// if(rand1 ==2){
// randomBallx=1;
// }
// if(rand2 ==1){
// randomBally =-1;
// }
// if(rand2==2){
// randomBally = 1;
// }
}
public PongPanel(){
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Color ball;
Color paddleOne;
Color paddleTwo;
ball = new Color(255,0,255);
paddleOne = new Color(255,0,0);
paddleTwo = new Color(0,0,255);
g.setColor(ball);
g.fillOval(ballStartX+randomBallx,ballStartY+randomBally,ballD,ballD);
g.setColor(paddleOne);
g.fillRect(20,paddleStart+y,paddleW1,paddleH1);
g.setColor(paddleTwo);
g.fillRect(760,paddleStarttwo+ytwo,paddleW2,paddleH2);
}
public void run() {
while(true){
ballNotZero();
detectPaddle();
randomBall();
ballMove();
repaint();
try {Thread.sleep(75); } catch(Exception e){
};
}
}
public static boolean intervallContains(int low, int high, int n) { //determines if something is in a certain range
return n >= low && n <= high;
}
public void detectPaddle(){ //determines if ball is close enough to paddle for detection
int withinY = (paddleStart+y) -(ballStartY+randomBally);
int withinY1 = (paddleStarttwo+ytwo)-(ballStartY+randomBally);
if (ballStartX+randomBallx <=20 && intervallContains(-50,50,withinY)){
dx = -dx;
}
if(ballStartX+randomBallx >=760 && intervallContains(-50,50,withinY1)){
dx = -dx;
}
}
public void randomBall(){
if(randomBallx >=0 ){
randomBallx+=dx;
}
if(randomBallx<0){
randomBallx-=dx;
}
if(randomBally>=0){
randomBally+=dy;
}
if(randomBally<0){
randomBally-=dy;
}
// randomBallx+=randomBallx;
// randomBally+=randomBally;
}
public void ballMove(){
if(ballStartY+randomBally > jpH-60){
dy= -dy;
}
if(ballStartY+randomBally <0){
dy = -dy;
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_QUOTE || e.getKeyCode() == KeyEvent.VK_SEMICOLON){
if(e.getKeyCode() == KeyEvent.VK_A){
y-=10;
}
if(e.getKeyCode() == KeyEvent.VK_S){
y+=10;
}
if(e.getKeyCode() == KeyEvent.VK_QUOTE){
ytwo-=10;
}
if(e.getKeyCode() == KeyEvent.VK_SEMICOLON){
ytwo+=10;
}
}
}
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Don't use while (true) but rather a Swing timer.
Don't use KeyListeners but rather Key Bindings.
Consider turning on a Swing Timer (which can act as your "background thread") that moves one paddle when the bindings detect the correct key has been pressed,
and stopping the timer that moves the paddle when the same key is released.
Same for the other paddle but of course having its actions respond to a bindings of a different pair of keys.
When attempting to get something like this working, try to get it working in a very simple program first, one without all the other junk required for your main program, but one which will allow you to test and prove your concept. Then if you get things working in your small program, great, you add the functionality to your main program. And if your small program code doesn't work and you need our help, you can post the small self-contained program here (an sscce) for us to test and modify.

Categories