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
Related
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;
}
}
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'm recreating the classic snake game. I've already finished coding the snake. What I have to do now is code the walls (that are supposed to be located at the edges of the frame).
As the painter of the snake "repaints" every 30 miliseconds, I thought it would not be really efficient to let this painter draw the walls as well, as the walls stay on the same place during the whole game so it isn't really necessary to redraw the walls every 30 miliseconds.
Thus, I was wondering whether it was possible to have two painters in my game, one that repaints the snake every 30 miliseconds, and one that paints only once (it paints the walls at the beginning of the game)? How should I do that?
These are the most important parts of the code related to the question (full code can be found below this):
//this is in the main class
public Snake(){
painter = new Painter(this);
this.add(painter, BorderLayout.CENTER);
this.setSize(500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(this);
this.requestFocusInWindow();
timer = new Timer(30, this);
startGame();
}
public void startGame(){
snakeList = new LinkedList<Point>();
snakeList.addFirst(new Point(10, 10));
snakeSegments(3);
setFood(30, 30);
movementX = 0;
movementY = 0;
timer.start(); //timer triggers gameUpdate();
}
public void gameUpdate(){
snakeMove(movementX, movementY);
snakeInstructor();
snakeEat();
snakeCollision();
painter.repaint();
}
-
// this is in the painter class
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
paintSnake(g);
paintFood(g);
}
This is the full code:
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Snake extends JFrame implements KeyListener, ActionListener{
Painter painter;
LinkedList<Point> snakeList;
Timer timer;
Point foodLocation;
int direction;
int snakeSize;
int movementX, movementY;
public static void main(String[] arg){
new Snake();
}
public Snake(){
painter = new Painter(this);
this.add(painter, BorderLayout.CENTER);
this.setSize(500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(this);
this.requestFocusInWindow();
timer = new Timer(30, this);
startGame();
}
public void startGame(){
snakeList = new LinkedList<Point>();
snakeList.addFirst(new Point(10, 10));
snakeSegments(3);
setFood(30, 30);
movementX = 0;
movementY = 0;
timer.start();
}
public void gameUpdate(){
snakeMove(movementX, movementY);
snakeInstructor();
snakeEat();
snakeCollision();
painter.repaint();
}
public void snakeCollision(){
for(int i = 4; i < getSnakeSize(); i++){
if(getFirst().equals(snakeList.get(i))){
gameOver();
}
}
}
public void gameOver(){
timer.stop();
}
public void snakeEat(){
if(getFirst().equals(getFood())){
newFood();
setSnakeSize();
snakeSegments(4);
}
}
public void snakeSegments(int i){
snakeSize = i;
while(snakeSize > 0){
snakeList.addLast(new Point(getLast()));
snakeSize--;
}
}
public void snakeInstructor(){
int currentDirection = getDirection();
if (currentDirection == 1){
snakeMove(-1, 0);
} else if (currentDirection == 2){
snakeMove(1, 0);
} else if (currentDirection == 3){
snakeMove(0, -1);
} else if (currentDirection == 4){
snakeMove(0, 1);
}
}
public void snakeMove(int directionX, int directionY){
snakeList.getFirst().x = snakeList.getFirst().x + directionX;
snakeList.getFirst().y = snakeList.getFirst().y + directionY;
for(int i = getSnakeSize()-1; i >=1; i--) {
snakeList.get(i).setLocation(snakeList.get(i-1));
}
}
public void newFood(){
Random generator = new Random();
int x = generator.nextInt(49);
int y = generator.nextInt(47);
setFood(x, y);
}
public void setFood(int x, int y){
foodLocation = new Point(x, y);
}
public Point getFood(){
return foodLocation;
}
public void setDirection(int newDirection){
direction = newDirection;
}
public int getDirection (){
return direction;
}
Point getFirst(){
return snakeList.getFirst();
}
Point getLast(){
return snakeList.getLast();
}
Point get(int i){
return snakeList.get(i);
}
public void addFirst(Point p){
snakeList.addFirst(p);
}
public void addLast(Point p){
snakeList.addLast(p);
}
public int getSnakeSize(){
return snakeList.size();
}
public void setSnakeSize(){
snakeSize = getSnakeSize() + 1;
}
#Override
public void actionPerformed(ActionEvent event) {
gameUpdate();
}
#Override public void keyReleased(KeyEvent e){ }
#Override public void keyTyped(KeyEvent e){ }
#Override public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if((key == KeyEvent.VK_LEFT) && direction != 2){
setDirection(1);
} else if ((key == KeyEvent.VK_RIGHT) && direction != 1){
setDirection(2);
} else if ((key == KeyEvent.VK_UP) && direction != 4){
setDirection(3);
} else if ((key == KeyEvent.VK_DOWN) && direction != 3){
setDirection(4);
} else if (key == KeyEvent.VK_SPACE){
startGame();
}
}
}
-
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class Painter extends JPanel{
Snake snake;
public Painter(Snake snake){
this.snake = snake;
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
paintSnake(g);
paintFood(g);
}
public void paintSnake(Graphics g){
for(int i = 0; i < snake.getSnakeSize(); i++){
g.setColor(Color.WHITE);
Point p = snake.snakeList.get(i);
g.fillRect(p.x*10, p.y*10, 10, 10);
}
}
public void paintFood(Graphics g){
Point p = snake.getFood();
g.setColor(Color.RED);
g.fillRect(p.x*10, p.y*10, 10, 10);
}
}
Yes and no...
You could make the Painter transparent and overlay the snake on top of the walls, but the call to g.fillRect(0, 0, 500, 500); would make that redundant, as it fills the entire component with the current color...
Seen as the paintComponent method for both painters would be called every time you want to update the UI, it's also kind of pointless.
A better solution would be to render the map to BufferedImage and paint it inside the painter before painting the snake.
I've switched from KeyListeners to KeyBindings as instructed, however they still seem to do nothing. My keybinds are set up as to allow the left and right arrow keys to call a setDx() method in paddle.java which instructs the move() method to move the paddle.
gamePanel.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class gamePanel extends JPanel implements ActionListener {
paddle Paddle;
boolean ingame = true;
int delay = 1000;
Timer timer;
JLabel text = new JLabel("stuff here");
InputMap im = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = this.getActionMap();
public gamePanel() {
setBackground(Color.WHITE);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "RightArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "LeftArrow");
add(text);
text.setBounds(100, 100, 200, 300);
timer = new Timer(delay, this);
Paddle = new paddle();
timer.start();
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (ingame) {
g.drawImage(Paddle.getImage(), Paddle.getX(), Paddle.getY(),
Paddle.getWidth(), Paddle.getHeight(), this);
}
}
#Override
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == timer) {
Paddle.move();
validate();
repaint();
}
}
public class ArrowAction extends AbstractAction {
private String cmd;
public ArrowAction(String cmd) {
this.cmd = cmd;
}
#Override
public void actionPerformed(ActionEvent e) {
if (cmd.equalsIgnoreCase("LeftArrow")) {
Paddle.setDx(-20);
} else if (cmd.equalsIgnoreCase("RightArrow")) {
Paddle.setDx(20);
}
}
}
/*
#Override
public void keyPressed(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
if (KeyCode == KeyEvent.VK_LEFT) {
text.setText("key pressed");
Paddle.setDx(-20);
}
if (KeyCode == KeyEvent.VK_RIGHT) {
Paddle.setDx(20);
}
}
#Override
public void keyReleased(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
if (KeyCode == KeyEvent.VK_LEFT) {
Paddle.setDx(0);
}
if (KeyCode == KeyEvent.VK_RIGHT) {
Paddle.setDx(0);
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
*/
}
Paddle.java:
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class paddle {
int dx = 0;
int x, y;
int height, width;
Image image;
public paddle() {
ImageIcon ii = new ImageIcon("src/Paddle.png");
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
//dx = 20;
resetState();
}
public void setDx(int z) {
dx = z;
}
public void move() {
x += dx;
if (x <= 2) {
x = 2;
}
if (x >= (640 - getWidth())) {
x = (640 - getWidth());
}
}
public void resetState() {
x = 250;
y = 375;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
Image getImage() {
return image;
}
Rectangle getRect() {
return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
}
}
If your KeyListener methods are not being called I suspect it's because the correct component does not have focus. It's difficult sometimes to manage what component has focus especially in a game, so I would suggest switching over to using key bindings which doesn't require components to have focus.
You never add the corresponding actions you the ActionMap
am.put("LeftArrow", new ArrowAction("LeftArrow"));
am.put("RightArrow", new ArrowAction("RightArrow"));
Also, if you don't repaint() in the actioPerformed of the ArrowAction, you won't see it update immediately, until repaint() is called by the Timer, which isn't very long, but still a miniscule delay.
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);
}
}