Java swing rendering phenomenon in 2D Game - java

I am currently working on my first jump'n Run game. The initial part is already working decent, but i still get a "bug" which appears when my "colums" are moving. This only happens when "MOVE_SPEED" is 1<. I tryed it with a Timer too, same thing.
This is how it looks like:
Please have a look at the code:
...
public class Board implements Runnable, KeyListener {
JFrame frame;
ArrayList<Column> cList;
Player p;
private boolean ingame = false;
public final static int INIT_WIDTH = 600;
public final static int INIT_HEIGHT = 400;
public static int WIDTH;
public static int HEIGHT;
private final int MOVE_SPEED = 10;
//When this is 1 the problem doesnt appear!
private final int GRAVITY = -3;
private int cPlayerStayingOn;
private double playerBottom;
private double floorTop;
private boolean mR = false;
private boolean mL = false;
private boolean jump = false;
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 100;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
private int fps;
private int lastFpsTime;
public static double delta = 1;
public Board() {
initBoard();
initPlayer();
initColumns();
}
private void initBoard() {
frame = new JFrame("Jump'nRun");
frame.setSize(INIT_WIDTH, INIT_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.addKeyListener(this);
cList = new ArrayList<Column>();
frame.setVisible(true);
Board.WIDTH = frame.getContentPane().getWidth();
Board.HEIGHT = frame.getContentPane().getHeight();
}
private void initColumns() {
for (int i = 0; i < 8; i++) {
cList.add(new Column(i + 1, true));
frame.add(cList.get(i));
}
}
private void initPlayer() {
p = new Player();
frame.add(p);
}
private void moveColums() {
for (Column col : cList) {
col.setLocation((int) (col.getLocation().getX() - MOVE_SPEED), 0);
}
}
private int playerStanding(double pX) {
for (int i = 0; i < 8; i++) {
if (cList.get(i).getX() <= pX
&& (cList.get(i).getX() + cList.get(i).getWidth()) >= pX) {
return i;
}
}
return -1;
}
private void movePlayer() {
// gravity
if (playerBottom < floorTop) {
p.setLocation((int) p.getLocation().getX(), (int) p.getLocation()
.getY() - GRAVITY);
}
if (mR) {
p.moveRight();
}
if (mL) {
p.moveLeft();
}
if (jump) {
p.jump();
jump = false;
}
}
private void collectData() {
this.cPlayerStayingOn = playerStanding(p.getBounds().getX()
+ p.getBounds().getWidth());
this.playerBottom = p.getBounds().getMaxY();
this.floorTop = cList.get(cPlayerStayingOn).floor.getY();
}
private void recycleColums() {
if (cList.get(0).getX() + cList.get(0).getWidth() <= 0) {
cList.remove(0);
cList.add(7, new Column(7 + 1, false));
frame.add(cList.get(7));
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE
|| e.getKeyCode() == KeyEvent.VK_W
|| e.getKeyCode() == KeyEvent.VK_UP) {
if (playerBottom >= floorTop) {
jump = true;
}
}
if (e.getKeyCode() == KeyEvent.VK_D
|| e.getKeyCode() == KeyEvent.VK_RIGHT) {
mR = true;
}
if (e.getKeyCode() == KeyEvent.VK_A
|| e.getKeyCode() == KeyEvent.VK_LEFT) {
mL = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_D
|| e.getKeyCode() == KeyEvent.VK_RIGHT) {
mR = false;
}
if (e.getKeyCode() == KeyEvent.VK_A
|| e.getKeyCode() == KeyEvent.VK_LEFT) {
mL = false;
}
}
private int getFps() {
return fps;
}
private void setFps(int fps) {
this.fps = fps;
}
#Override
public void run() {
while (true) {
if (!ingame) {
ingame = true;
} else {
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
delta = updateLength / ((double) OPTIMAL_TIME);
lastFpsTime += updateLength;
setFps(getFps() + 1);
if (lastFpsTime >= 1000000000) {
lastFpsTime = 0;
setFps(0);
}
recycleColums();
collectData();
moveColums();
movePlayer();
try {
Thread.sleep((lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000);
} catch (Exception e) {
}
}
}
}
}
and the Column Class:
...
public class Column extends JPanel {
JPanel floor;
JPanel grass;
Random rand = new Random();
private static final long serialVersionUID = 1L;
public final static int WIDTH = Board.WIDTH / 6;
public final int HEIGHT = Board.HEIGHT;
private int position;
public final static int FLOOR_H = WIDTH;
public Column(int pos, boolean init) {
this.position = pos;
setBounds((WIDTH * position) - WIDTH, 0, WIDTH, HEIGHT);
setLayout(null);
setBackground(Color.WHITE);
floor = new JPanel();
floor.setLayout(null);
floor.setBackground(Color.BLACK);
if (init) {
floor.setBounds(0, HEIGHT - FLOOR_H, WIDTH, FLOOR_H);
} else {
floor.setBounds(0,
(HEIGHT - (FLOOR_H + (FLOOR_H * rand.nextInt(2) / 2))),
WIDTH, FLOOR_H * 2);
}
grass = new JPanel();
grass.setBounds(0, 0, WIDTH, 10);
grass.setBackground(Color.GREEN);
floor.add(grass);
add(floor);
}
}
Any hints are appreciatet!
(Sorry for the bad english)

i fixed it by changing the following:
private void recycleColums() {
if (cList.get(0).getX() + cList.get(0).getWidth() <= 0) {
cList.remove(0);
cList.add(7, new Column(7 + 1, false, cList.get(6).getX()));
frame.add(cList.get(7));
}
}
...
public Column(int pos, boolean init, int lastX) {
this.position = pos;
setLayout(null);
setBackground(Color.WHITE);
floor = new JPanel();
floor.setLayout(null);
floor.setBackground(Color.BLACK);
if (init) {
setBounds((WIDTH * position) - WIDTH, 0, WIDTH, HEIGHT);
floor.setBounds(0, HEIGHT - FLOOR_H, WIDTH, FLOOR_H);
} else {
setBounds(lastX + WIDTH, 0, WIDTH, HEIGHT);
floor.setBounds(0,
(HEIGHT - (FLOOR_H + (FLOOR_H * rand.nextInt(2) / 2))),
WIDTH, FLOOR_H * 2);
}

Related

Can't seem to get a missile to bounce of the walls on a simple java programming game

Okay, so I am trying to create a simple game where you shoot a missile and if it hits a wall it has to bounce back expect for the bottom wall were it will inactivate the missile to allow me to shoot a new missile.
import java.awt.*;
public class Project2{
public static final int PANEL_WIDTH = 300;
public static final int PANEL_HEIGHT = 300;
public static final int SLEEP_TIME = 50;
public static final Color SHOOTER_COLOR = Color.RED;
public static final Color BACKGROUND_COLOR = Color.WHITE;
public static final int SHOOTER_SIZE = 20; //diameter of the shooter
public static final int GUN_SIZE = 10; //length og the gun
public static final int SHOOTER_POSITION_Y = PANEL_HEIGHT - SHOOTER_SIZE;
public static final int SHOOTER_INITIAL_POSITION_X = 150;
public static int shooterPositionX;
public static int gunPositionX;
public static int gunPositionY;
public static int targetPositionX;
public static final Color TARGET_COLOR = Color.BLUE;
public static final int TARGET_POSITION_Y = 50;
public static final int TARGET_SIZE = 20;
public static final int KEY_SPACE =32;
public static final int KEY_PAGE_UP = 33;
public static final int KEY_HOME = 36;
public static final int KEY_LEFT_ARROW = 37;
public static final int KEY_UP_ARROW = 38;
public static final int KEY_RIGHT_ARROW = 39;
public static final int KEY_DOWN_ARROW = 40;
public static double missilePositionX;
public static double missilePositionY;
public static double missileDeltaX;
public static double missileDeltaY;
public static boolean missileActive;
public static final Color MISSILE_COLOR = Color.BLACK;
public static final int MISSILE_SIZE =2;
public static final double MISSILE_SPEED =1.0;
public static int hitCount;
public static final int TARGET_DELTA_X= 1;
public static int targetDeltaX;
// public static final Random.nextDouble();
public static void initialize(){
shooterPositionX = SHOOTER_INITIAL_POSITION_X;
gunPositionX = 0;
gunPositionY = GUN_SIZE;
targetPositionX = 150;
missileActive = false;
hitCount = 0;
targetDeltaX = 0;
}
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(PANEL_WIDTH, PANEL_HEIGHT);
Graphics g = panel.getGraphics( );
initialize();
startGame(panel, g);
}
public static void drawAll(Graphics g){
g.setColor(Color.BLACK);
g.drawString("Project 2 by JR", 10, 15); // fix ""
g.drawString("Hits: " + hitCount, 10, 30);
// for(int i=0, i<=hitCount; i++){
//
// }
// Hits: followed by a number of stars corresponding to the hit count.
//Do not do this by calling g.drawString in a loop. Instead, make a single string with a
//for loop, appending the appropriate number of stars. Then call g.drawString once.
drawShooter(g, SHOOTER_COLOR);
drawTarget(g, TARGET_COLOR);
}
public static void startGame(DrawingPanel panel, Graphics g) {
for (int i = 0; i <= 10000; i++) {
panel.sleep(SLEEP_TIME);
handleKeys(panel, g);
// moveTarget(g);
drawAll(g);
moveMissile(g);
}
}
public static void drawShooter(Graphics g, Color c){
g.setColor(c);
g.fillOval(shooterPositionX-SHOOTER_SIZE/2, SHOOTER_POSITION_Y-SHOOTER_SIZE, SHOOTER_SIZE, SHOOTER_SIZE);
g.drawLine(shooterPositionX, SHOOTER_POSITION_Y-SHOOTER_SIZE, shooterPositionX+gunPositionX, SHOOTER_POSITION_Y-SHOOTER_SIZE - GUN_SIZE);
}
public static void drawTarget(Graphics g, Color c){
g.setColor(c);
g.fillOval(targetPositionX-TARGET_SIZE/2, TARGET_POSITION_Y-TARGET_SIZE, TARGET_SIZE, TARGET_SIZE);
g.drawLine(targetPositionX-TARGET_SIZE, TARGET_POSITION_Y+TARGET_SIZE/2, targetPositionX+TARGET_SIZE, TARGET_POSITION_Y+TARGET_SIZE/2);
}
public static void moveShooter(Graphics g, int deltaX){
drawShooter(g, BACKGROUND_COLOR);
shooterPositionX += deltaX;
drawShooter(g, SHOOTER_COLOR);
//does not allow you to move any part of the shooter off the screen.
}
public static void handleKeys(DrawingPanel panel, Graphics g){
int keyCode = panel.getKeyCode();
if (keyCode == KEY_SPACE)
reset(g);
else if (keyCode == KEY_RIGHT_ARROW)
moveShooter(g,1);
else if (keyCode == KEY_LEFT_ARROW)
moveShooter(g,-1);
else if (keyCode == KEY_HOME)
moveGun(g,1);
else if (keyCode == KEY_PAGE_UP)
moveGun(g,-1);
else if(keyCode == KEY_UP_ARROW)
shootMissile(g);
}
public static void reset(Graphics g){
g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0, PANEL_WIDTH, PANEL_HEIGHT);
initialize();
}
public static void moveGun(Graphics g, int deltaX){
drawShooter(g, BACKGROUND_COLOR);
gunPositionX += deltaX;
drawShooter(g, SHOOTER_COLOR);
//Do not let gunPositionX have an absolute value larger than SHOOTER_SIZE.
}
public static void shootMissile(Graphics g){
if(missileActive == false){
missileActive = true;
missilePositionX = shooterPositionX;
missilePositionY = SHOOTER_POSITION_Y-SHOOTER_SIZE;
missileDeltaX = 0;
missileDeltaY = 0;
missilePositionX += missileDeltaX;
missilePositionY += missileDeltaY;
}
}
public static void moveMissile(Graphics g){
if(missileActive){
drawMissile(g, BACKGROUND_COLOR);
missilePositionX += missileDeltaX;
missilePositionY += missileDeltaY;
drawMissile(g, MISSILE_COLOR);
if(missilePositionY <= 0){
missileDeltaY = -Math.abs(missileDeltaY);
missilePositionY += missileDeltaY;
}
else if(missilePositionX >= 300){
missilePositionX += missileDeltaX;
}
else if(missilePositionX <=0){
missileDeltaX = -Math.abs(missileDeltaX);
missilePositionX += missileDeltaX;
}
else if(missilePositionY >= 300){
drawMissile(g, BACKGROUND_COLOR);
missileActive = false;
}
if( detectHitTarget((int)missilePositionX, (int)missilePositionY, (int)MISSILE_SIZE/2, targetPositionX, TARGET_POSITION_Y, TARGET_SIZE/2)){
hitCount ++;
drawMissile(g, BACKGROUND_COLOR);//erase the missile;
missileActive = false;
}
}
}
public static void drawMissile(Graphics g, Color c){
g.setColor(c);
g.fillOval((int)missilePositionX, (int)missilePositionY, MISSILE_SIZE, MISSILE_SIZE);
missileDeltaY = - gunPositionY * MISSILE_SPEED;
missileDeltaX = gunPositionX * MISSILE_SPEED;
}
public static boolean detectHitTarget(int x1, int y1, int r1, int x2, int y2, int r2){
if(Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)) <= r1 + r2){
return true;
}else{
return false;}
}
public static void moveTarget(Graphics g){
// drawTarget(g, BACKGROUND_COLOR);
// targetPositionX += targetDeltaX;
// if(targetPositionX >= 0){
// targetPositionX = +Math.abs(targetDelta);
// }
// else if(targetPositionX <=300){
// targetPositionX = -Math.abs(targetDelta);
// }
// if(Random >= .98){
// targetDeltaX = 0;
// }
// else if(Random >= .96){
// targetDeltaX =1;
// }
// else if(Random >= .94){
// targetDleta = -1;
// }
}
}
so far the ball is just getting 'stuck' to the top wall or not even getting 'stuck' in the case of the side walls just going off the panel, instead of bouncing off and I can't seem to figure it out.
Drawing Panel
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class DrawingPanel implements ActionListener {
private static final String versionMessage =
"Drawing Panel version 1.1, January 25, 2015";
private static final int DELAY = 100; // delay between repaints in millis
private static final boolean PRETTY = false; // true to anti-alias
private static boolean showStatus = false;
private static final int MAX_KEY_BUF_SIZE = 10;
private int width, height; // dimensions of window frame
private JFrame frame; // overall window frame
private JPanel panel; // overall drawing surface
private BufferedImage image; // remembers drawing commands
private Graphics2D g2; // graphics context for painting
private JLabel statusBar; // status bar showing mouse position
private volatile MouseEvent click; // stores the last mouse click
private volatile boolean pressed; // true if the mouse is pressed
private volatile MouseEvent move; // stores the position of the mouse
private ArrayList<KeyInfo> keys;
// construct a drawing panel of given width and height enclosed in a window
public DrawingPanel(int width, int height) {
this.width = width;
this.height = height;
keys = new ArrayList<KeyInfo>();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
statusBar = new JLabel(" ");
statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
statusBar.setText(versionMessage);
panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
panel.setBackground(Color.WHITE);
panel.setPreferredSize(new Dimension(width, height));
panel.add(new JLabel(new ImageIcon(image)));
click = null;
move = null;
pressed = false;
// listen to mouse movement
MouseInputAdapter listener = new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
pressed = false;
move = e;
if (showStatus)
statusBar.setText("moved (" + e.getX() + ", " + e.getY() + ")");
}
public void mousePressed(MouseEvent e) {
pressed = true;
move = e;
if (showStatus)
statusBar.setText("pressed (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseDragged(MouseEvent e) {
pressed = true;
move = e;
if (showStatus)
statusBar.setText("dragged (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
click = e;
pressed = false;
if (showStatus)
statusBar.setText("released (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
// System.out.println("mouse entered");
panel.requestFocus();
}
};
panel.addMouseListener(listener);
panel.addMouseMotionListener(listener);
new DrawingPanelKeyListener();
g2 = (Graphics2D)image.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.1f));
}
frame = new JFrame("Drawing Panel");
frame.setResizable(false);
try {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // so that this works in an applet
} catch (Exception e) {}
frame.getContentPane().add(panel);
frame.getContentPane().add(statusBar, "South");
frame.pack();
frame.setVisible(true);
toFront();
frame.requestFocus();
// repaint timer so that the screen will update
new Timer(DELAY, this).start();
}
public void showMouseStatus(boolean f) {
showStatus = f;
}
public void addKeyListener(KeyListener listener) {
panel.addKeyListener(listener);
panel.requestFocus();
}
// used for an internal timer that keeps repainting
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
// obtain the Graphics object to draw on the panel
public Graphics2D getGraphics() {
return g2;
}
// set the background color of the drawing panel
public void setBackground(Color c) {
panel.setBackground(c);
}
// show or hide the drawing panel on the screen
public void setVisible(boolean visible) {
frame.setVisible(visible);
}
// makes the program pause for the given amount of time,
// allowing for animation
public void sleep(int millis) {
panel.repaint();
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
// close the drawing panel
public void close() {
frame.dispose();
}
// makes drawing panel become the frontmost window on the screen
public void toFront() {
frame.toFront();
}
// return panel width
public int getWidth() {
return width;
}
// return panel height
public int getHeight() {
return height;
}
// return the X position of the mouse or -1
public int getMouseX() {
if (move == null) {
return -1;
} else {
return move.getX();
}
}
// return the Y position of the mouse or -1
public int getMouseY() {
if (move == null) {
return -1;
} else {
return move.getY();
}
}
// return the X position of the last click or -1
public int getClickX() {
if (click == null) {
return -1;
} else {
return click.getX();
}
}
// return the Y position of the last click or -1
public int getClickY() {
if (click == null) {
return -1;
} else {
return click.getY();
}
}
// return true if a mouse button is pressed
public boolean mousePressed() {
return pressed;
}
public synchronized int getKeyCode() {
if (keys.size() == 0)
return 0;
return keys.remove(0).keyCode;
}
public synchronized char getKeyChar() {
if (keys.size() == 0)
return 0;
return keys.remove(0).keyChar;
}
public synchronized int getKeysSize() {
return keys.size();
}
private synchronized void insertKeyData(char c, int code) {
keys.add(new KeyInfo(c,code));
if (keys.size() > MAX_KEY_BUF_SIZE) {
keys.remove(0);
// System.out.println("Dropped key");
}
}
private class KeyInfo {
public int keyCode;
public char keyChar;
public KeyInfo(char keyChar, int keyCode) {
this.keyCode = keyCode;
this.keyChar = keyChar;
}
}
private class DrawingPanelKeyListener implements KeyListener {
int repeatCount = 0;
public DrawingPanelKeyListener() {
panel.addKeyListener(this);
panel.requestFocus();
}
public void keyPressed(KeyEvent event) {
// System.out.println("key pressed");
repeatCount++;
if ((repeatCount == 1) || (getKeysSize() < 2))
insertKeyData(event.getKeyChar(),event.getKeyCode());
}
public void keyTyped(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
repeatCount = 0;
}
}
}
Your drawMissile method which is called inside moveMissile method everytime it is called it is re-initializing the missileDeltaY and missileDeltaX variables.
missileDeltaY = - gunPositionY * MISSILE_SPEED;
missileDeltaX = gunPositionX * MISSILE_SPEED;
So no matter what calculations take place in the rest body of the moveMissile method, those variables will take their default values hence no change of the trajectory when hitting the boundaries.
I have made some changes in your methods to help you figure out the solution, it looks like it is working if you shoot the missile to hit the left boundary
shootMissile
public static void shootMissile(Graphics g){
if(missileActive == false){
missileActive = true;
missilePositionX = shooterPositionX;
missilePositionY = SHOOTER_POSITION_Y-SHOOTER_SIZE;
missileDeltaX = 0;
missileDeltaY = 0;
missilePositionX += missileDeltaX;
missilePositionY += missileDeltaY;
missileDeltaY = - gunPositionY * MISSILE_SPEED;
missileDeltaX = gunPositionX * MISSILE_SPEED;
}
}
moveMissile
public static void moveMissile(Graphics g){
if(missileActive){
drawMissile(g, BACKGROUND_COLOR);
missilePositionX += missileDeltaX;
missilePositionY += missileDeltaY;
drawMissile(g, MISSILE_COLOR);
if(missilePositionY <= 0){
missileDeltaY = Math.abs(missileDeltaY);
missilePositionY += missileDeltaY;
}
if(missilePositionX >= 300){
missilePositionX += -Math.abs(missileDeltaX);
}
if(missilePositionX <=0){
missileDeltaX = Math.abs(missileDeltaX);
missilePositionX += missileDeltaX;
}
if(missilePositionY >= 300){
drawMissile(g, BACKGROUND_COLOR);
missileActive = false;
}
if( detectHitTarget((int)missilePositionX, (int)missilePositionY, (int)MISSILE_SIZE/2, targetPositionX, TARGET_POSITION_Y, TARGET_SIZE/2)){
hitCount ++;
drawMissile(g, BACKGROUND_COLOR);//erase the missile;
missileActive = false;
}
}
}
drawMissile
public static void drawMissile(Graphics g, Color c){
g.setColor(c);
g.fillOval((int)missilePositionX, (int)missilePositionY, MISSILE_SIZE, MISSILE_SIZE);
}

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

Typing game: choosing two words

I'm creating a game like zType
and I have a problem in validating the input. As you can see in the picture below it select two words. How can I fix this problem, please help.
This is My Game class
import java.awt.Canvas;
import java.awt.event.KeyListener;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener
{
public static final int WIDTH = 640;
public static final int HEIGHT = 680;
public final String TITLE = "Game";
private boolean running = false;
private Thread thread;
private BufferedImage spriteSheet = null;
private BufferedImage background = null;
public int level = 1;
public int fps = 0;
public int score = 0;
private int enemy_count = 15;
private int enemy_killed = 0;
private int enemy_notkilled = 0;
private boolean target = false;
public String t = "";
private Controller c;
private Textures tex;
private LinkedList<Enemy> e = new LinkedList<Enemy>();
private Enemy enemy;
public void init()
{
requestFocus();
try
{
spriteSheet = ImageIO.read(getClass().getResource("/sprite_sheet.png"));
background = ImageIO.read(getClass().getResource("/background.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
tex = new Textures(this);
c = new Controller(tex, this);
addKeyListener(this);
c.createEnemy(enemy_count);
e = c.getEnemy();
}
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);
}
public void run()
{
init();
long lastTime = System.nanoTime();
final double amountOfTicks= 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1)
{
update();
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
fps = frames;
frames = 0;
}
}
stop();
}
private void update()
{
c.update();
if(enemy_killed + enemy_notkilled >= enemy_count)
{
e.clear();
t = "";
level++;
enemy_killed = 0;
enemy_notkilled = 0;
c.createEnemy(enemy_count);
}
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(background, 0, 0, null);
c.render(g);
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent ek)
{
int key = ek.getKeyCode();
char character = Character.toLowerCase(ek.getKeyChar());
boolean result = isValid(key);
if(result && !target)
{
for(int i = 0; i < e.size(); i++)
if(e.get(i).getFirstLetter() == character && e.get(i).getOnScreen())
{
enemy = e.get(i);
t = enemy.getText();
if(enemy.getCurrentIndex() == 0)
enemy.addCurrentIndex();
target = true;
System.out.println("---"+enemy.text);
break;
}
}
else if(result && t.charAt(enemy.getCurrentIndex()) == character)
enemy.addCurrentIndex();
}
public void keyReleased(KeyEvent ek){ }
public void keyTyped(KeyEvent ek){ }
public static void main(String[] args)
{
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
public boolean isValid(int key)
{
return key >= 65 && key <= 90 ? true : false;
}
public BufferedImage getSpriteSheet()
{
return spriteSheet;
}
public int getEnemy_count()
{
return enemy_count;
}
public void setEnemy_count(int enemy_count)
{
this.enemy_count = enemy_count;
}
public int getEnemy_killed()
{
return enemy_killed;
}
public void setEnemy_killed(int enemy_killed)
{
this.enemy_killed = enemy_killed;
}
public int getEnemy_notkilled()
{
return enemy_notkilled;
}
public void setEnemy_notkilled(int enemy_notkilled)
{
this.enemy_notkilled = enemy_notkilled;
}
public void addScore(int k)
{
score += k;
}
public void falseTarget()
{
target = false;
}
public String getT()
{
return t;
}
public void setT(String k)
{
t = k;
}
}
This is my Enemy Class
import java.awt.*;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
public class Enemy
{
private double x ,y;
public String text;
private char firstLetter;
private AttributedString as;
private Controller c;
private Textures tex;
private Game game;
private int currentIndex = 0;
private int textLength = 0;
private double speed = 0.0;
private int stringWidth = 0;
private boolean onScreen = false;
public Enemy(double x, double y, double speed, Textures tex, Controller c, Game game, String text, int stringWidth)
{
this.x = x;
this.y = y;
this.tex = tex;
this.text = text;
this.game = game;
this.c = c;
this.speed = speed;
firstLetter = this.text.charAt(0);
textLength = this.text.length();
this.stringWidth = stringWidth;
}
public void update()
{
y += speed;
if(y >= 0)
onScreen = true;
if(currentIndex >= textLength)
{
game.addScore(5);
game.setT("");
c.removeEnemy(this);
game.setEnemy_killed(game.getEnemy_killed() + 1);
game.falseTarget();
}
if(y >= Game.HEIGHT - 50)
{
//game.decreaseHealth();
game.setT("");
c.removeEnemy(this);
game.setEnemy_notkilled(game.getEnemy_notkilled() + 1);
game.falseTarget();
game.t ="";
}
}
public void render(Graphics g)
{
g.drawImage(tex.enemy, (int)x, (int)y, null);
as = new AttributedString(text);
if(currentIndex >= 1)
as.addAttribute(TextAttribute.FOREGROUND, Color.WHITE, 0, currentIndex);
as.addAttribute(TextAttribute.FONT, new Font("Consolas", Font.BOLD, 12), 0, text.length());
g.drawString(as.getIterator(), (int)x + getAdd(stringWidth), (int)y + 13);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public String getText()
{
return text;
}
public char getFirstLetter()
{
return firstLetter;
}
public void addCurrentIndex()
{
currentIndex++;
}
public int getCurrentIndex()
{
return currentIndex;
}
public int getTextLength()
{
return textLength;
}
public int getAdd(int width)
{
return (96 / 2) - (width / 2);
}
public boolean getOnScreen()
{
return onScreen;
}
}
The problem is that you're calling falseTarget() whenever an enemy moves out of the screen. In your example, you assigned target = true when you pressed the 'o' (for the enemy named "owe"), but then a different enemy (maybe "jet", maybe an enemy that is no longer visible) finished "dropping" out of the screen (y >= Game.HEIGHT - 50), so you called falseTarget() - and thus, when you pressed 'i' you started a new enemy ("ice").
What you want to do is call falseTarget() in this case only if the enemy that dropped out of the screen is the one that's currently being targeted:
if(y >= Game.HEIGHT - 50)
{
//game.decreaseHealth();
//game.setT(""); // <-- Commented this line out
c.removeEnemy(this);
game.setEnemy_notkilled(game.getEnemy_notkilled() + 1);
if(game.getT().equals(text)) // <-- Added this if before calling falseTarget()
{ // and clearing the game's current enemy text
game.falseTarget();
game.t ="";
}
}

Getting NPE in 2D Game thread

I keep getting a NPE when I run this very basic 2D game. It has something to do with the Key Events but I am not sure how to fix this. Can someone help me? It says the NPE is on this line if (_input.up.isPressed()) {
Here is the InputHandler Class
public class InputHandler implements KeyListener {
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private boolean pressed = false;
public void toggle(boolean isPressed) {
pressed = isPressed;
}
public boolean isPressed() {
return pressed;
}
}
// public List<Key> keys = new ArrayList<Key>();
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int keyCode, boolean isPressed) {
if (keyCode == KeyEvent.VK_W) {
up.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_S) {
down.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_A) {
left.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_D) {
right.toggle(isPressed);
}
}
}
here is the Player Class
public class Player extends Mob {
private InputHandler _input;
private int _speed;
private int _r = 10;
private int _x, _y;
public Player(int x, int y, int speed, InputHandler input) {
super("Player", x, y, 1);
_input = input;
_speed = speed;
_x = x;
_y = y;
}
public boolean hasCollided(int dx, int dy) {
return false;
}
public void update() {
int dx = 0;
int dy = 0;
if (_input.up.isPressed()) {
dy--;
} else if (_input.down.isPressed()) {
dy++;
} else if (_input.left.isPressed()) {
dx--;
} else if (_input.right.isPressed()) {
dx++;
}
if (dx != 0 || dy != 0) {
move(dx, dy);
isMoving = true;
} else {
isMoving = false;
}
if (_x < _r)
_x = _r;
if (_y < _r)
_y = _r;
if (_x > Game.WIDTH - _r)
_x = Game.WIDTH - _r;
if (_y > Game.HEIGHT - _r)
_y = Game.HEIGHT - _r;
}
public void render(Graphics2D g) {
g.setColor(Color.BLACK);
g.fillOval(x - _r, y - _r, 2 * _r, 2 * _r);
g.setStroke(new BasicStroke(3));
g.setColor(Color.GRAY);
g.drawOval(x - _r, y - _r, 2 * _r, 2 * _r);
g.setStroke(new BasicStroke(1));
}
}
here is the game class which creates the player
public class Game extends Canvas implements Runnable {
private static Game _instance;
private static final String TITLE = "ProjectG";
public static final int WIDTH = 960;
public static final int HEIGHT = WIDTH * 3 / 4;
private static final int SCALE = 1;
// to make it have a higher resolution double the width and height but half
// the scale. You are doubling the width and height but keeping the same
// window size by reducing the scale
public static final Dimension SIZE = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
private static final int UPDATE_RATE = 60;
private static final int RENDER_RATE = 60;
private JFrame _frame;
private Thread _thread;
private boolean _running = false;
private int _tps = 0;
private int _fps = 0;
private int _totalTicks = 0;
private BufferedImage image;
private Graphics2D g;
public InputHandler input;
private Player player;
public Game() {
_instance = this;
setPreferredSize(SIZE);
setMinimumSize(SIZE);
setMaximumSize(SIZE);
_frame = new JFrame(TITLE);
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.setLayout(new BorderLayout());
_frame.add(_instance, BorderLayout.CENTER);
_frame.pack();
_frame.setResizable(false);
_frame.setLocationRelativeTo(null);
_frame.setVisible(true);
player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2, 1, input);
}
public synchronized void start() {
_running = true;
_thread = new Thread(this, TITLE + "_main");
_thread.start();
}
public synchronized void stop() {
_running = false;
if (_thread != null) {
try {
_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void run() {
double lastUpdateTime = System.nanoTime();
double lastRenderTime = System.nanoTime();
final int ns = 1000000000;
final double nsPerUpdate = (double) ns / UPDATE_RATE;
final double nsPerRender = (double) ns / RENDER_RATE;
final int maxUpdatesBeforeRender = 1;
int lastSecond = (int) lastUpdateTime / ns;
int tickCount = 0;
int renderCount = 0;
image = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
while (_running) {
long currTime = System.nanoTime();
int tps = 0;
while ((currTime - lastUpdateTime) > nsPerUpdate && tps < maxUpdatesBeforeRender) {
update();
tickCount++;
_totalTicks++;
tps++;
lastUpdateTime += nsPerUpdate;
}
if (currTime - lastUpdateTime > nsPerUpdate) {
lastUpdateTime = currTime - nsPerUpdate;
}
float interpolation = Math.min(1.0F, (float) ((currTime - lastUpdateTime) / nsPerUpdate));
render(interpolation);
draw();
renderCount++;
lastRenderTime = currTime;
int currSecond = (int) (lastUpdateTime / ns);
if (currSecond > lastSecond) {
_tps = tickCount;
_fps = renderCount;
tickCount = 0;
renderCount = 0;
lastSecond = currSecond;
System.out.println(_tps + " TPS " + _fps + " FPS");
}
while (currTime - lastRenderTime < nsPerRender && currTime - lastUpdateTime < nsPerUpdate) {
Thread.yield();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
currTime = System.nanoTime();
}
}
}
public void update() {
player.update();
}
public void render(float interpolation) {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
}
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
g.setColor(Color.BLACK);
g.drawString("TPS: " + _fps + " FPS: " + _fps, 10, 20);
player.render(g);
}
public void draw() {
Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
public Game getGame() {
return this;
}
}
You haven't initialized input, so what you pass to
player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2, 1, input);
is null. You need to initialize it before
input = new InputHandler(this);

Simple way on how control sprite animation speed

I'm new to programming and I have some issues on how to control my animation's speed. And I hope that you can give me some tips for this code.
public class Maze extends Canvas {
Map map;
Mario mario;
private Timer time;
private BufferStrategy strategy;
private int move;
boolean gameRunning = true;
public Maze(){
map = new Map();
mario = new Mario();
JFrame frame = new JFrame();
frame.setTitle("SuperMario2D");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(438, 438));
panel.setLayout(null);
setBounds(0, 0, 454, 476);
panel.add(this);
setIgnoreRepaint(true);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
addKeyListener(new KeyHandler());
requestFocus();
createBufferStrategy(2);
strategy = getBufferStrategy();
}
public void gameLoop() {
long lastLoopTime = System.currentTimeMillis();
while (gameRunning) {
// work out how long its been since the last update, this
// will be used to calculate how far the entities should
// move this loop
long delta = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0,0,800,600);
map.draw(g);
mario.draw(g, move);
g.dispose();
strategy.show();
}
try {
Thread.sleep(10);
} catch (Exception e) {}
}
public class KeyHandler extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_UP){
mario.move(0, -1); //if it's not equal this will not execute because Y-1 will equal to w
move = 1;
System.out.println("You press up");
}
if(keycode == KeyEvent.VK_DOWN){
mario.move(0, 1);
move = 2;
System.out.println("You press down");
}
if(keycode == KeyEvent.VK_LEFT){
mario.move(-1, 0);
move = 3;
System.out.println("You press left");
}
if(keycode == KeyEvent.VK_RIGHT){
mario.move(1, 0);
move = 4;
System.out.println("You press right");
}
}
public void keyReleased(KeyEvent e){
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_UP){
move = 5;
System.out.println("You released up");
}
if(keycode == KeyEvent.VK_DOWN){
move = 6;
System.out.println("You released down");
}
if(keycode == KeyEvent.VK_LEFT){
move = 7;
System.out.println("You released down");
}
if(keycode == KeyEvent.VK_RIGHT){
move = 8;
System.out.println("You released down");
}
}
public void keyTyped(KeyEvent e){
}
}
public static void main(String[] args){
Maze maze = new Maze();
maze.gameLoop();
}
}
here is the code that loads my animated images
public class Mario {
private int x, y;
private int tileX, tileY; //for collision
//private Image player;
private Image[] playerDown = new Image[3];
private Image[] playerUp = new Image[3];
private Image[] playerLeft = new Image[3];
private Image[] playerRight = new Image[3];
private Image[] playerJumpD = new Image[3];
private Image[] playerJumpU = new Image[3];
private Image[] playerJumpL = new Image[3];
private Image[] playerJumpR = new Image[3];
private int cycle = 0;
private long scene1 = 0;
private long scene2 = 500;
public Mario(){
moveDown();
moveUp();
moveLeft();
moveRight();
/*
//jump
jumpDown();
jumpUp();
jumpLeft();
jumpRight();
*/
tileX = 1;
tileY = 1;
}
public void moveDown(){
playerDown[0] = new ImageIcon("images/marioFW1.png").getImage();
playerDown[1] = new ImageIcon("images/marioFW2.png").getImage();
playerDown[2] = new ImageIcon("images/marioFW3.png").getImage();
}
public void moveUp(){
playerUp[0] = new ImageIcon("images/marioB1.png").getImage();
playerUp[1] = new ImageIcon("images/marioB2.png").getImage();
playerUp[2] = new ImageIcon("images/marioB3.png").getImage();
}
public void moveLeft(){
playerLeft[0] = new ImageIcon("images/marioJW1.png").getImage();
playerLeft[1] = new ImageIcon("images/marioJW2.png").getImage();
playerLeft[2] = new ImageIcon("images/marioJW3.png").getImage();
}
public void moveRight(){
playerRight[0] = new ImageIcon("images/marioR1.png").getImage();
playerRight[1] = new ImageIcon("images/marioR2.png").getImage();
playerRight[2] = new ImageIcon("images/marioR3.png").getImage();
}
/*
//jump
public void jumpDown(){
playerJumpD[0] = new ImageIcon("images/marioFJ1.png").getImage();
playerJumpD[1] = new ImageIcon("images/marioFJ2.png").getImage();
playerJumpD[2] = new ImageIcon("images/marioFJ3.png").getImage();
}
public void jumpUp(){
playerJumpU[0] = new ImageIcon("images/marioBJ1.png").getImage();
playerJumpU[1] = new ImageIcon("images/marioBJ2.png").getImage();
playerJumpU[2] = new ImageIcon("images/marioBJ3.png").getImage();
}
public void jumpLeft(){
playerJumpL[0] = new ImageIcon("images/marioJL1.png").getImage();
playerJumpL[1] = new ImageIcon("images/marioJL2.png").getImage();
playerJumpL[2] = new ImageIcon("images/marioJL3.png").getImage();
}
public void jumpRight(){
playerJumpR[0] = new ImageIcon("images/marioRJ1.png").getImage();
playerJumpR[1] = new ImageIcon("images/marioRJ2.png").getImage();
playerJumpR[2] = new ImageIcon("images/marioRJ3.png").getImage();
}
*/
public void move(int dx, int dy){
// x += dx;
// y += dy;
tileX += dx;
tileY += dy;
}
public Image getMoveDown(){
if(cycle == playerDown.length){
cycle = 0;
}
return playerDown[cycle++];
}
public Image getMoveUp(){
if(cycle == playerUp.length){
cycle = 0;
}
return playerUp[cycle++];
}
public Image getMoveLeft(){
if(cycle == playerLeft.length){
cycle = 0;
}
return playerLeft[cycle++];
}
public Image getMoveRight(){
if(cycle == playerRight.length){
cycle = 0;
}
return playerRight[cycle++];
}
/*
//jump
public Image getJumpD(){
if(cycle == playerJumpR.length){
cycle = 0;
}
return playerJumpR[cycle++];
}
public Image getJumpU(){
if(cycle == playerJumpU.length){
cycle = 0;
}
return playerJumpU[cycle++];
}
public Image getJumpL(){
if(cycle == playerJumpL.length){
cycle = 0;
}
return playerJumpL[cycle++];
}
public Image getJumpR(){
if(cycle == playerJumpR.length){
cycle = 0;
}
return playerJumpR[cycle++];
}
*/
/*
public void checkMove(){
if (System.currentTimeMillis() - scene1 < scene2) {
return;
}
scene1 = System.currentTimeMillis();
}
*/
public int getTileX(){
return tileX;
}
public int getTileY(){
return tileY;
}
public void draw(Graphics g, int move) {
if(move == 0)
g.drawImage(playerDown[1], getTileX(), getTileY(), null );
if(move == 1)
g.drawImage(getMoveUp(), getTileX(), getTileY(), null );
if(move == 2)
g.drawImage(getMoveDown(), getTileX(), getTileY(), null );
if(move == 3)
g.drawImage(getMoveLeft(), getTileX(), getTileY(), null );
if(move == 4)
g.drawImage(getMoveRight(), getTileX(), getTileY(), null );
if(move == 5)
g.drawImage(playerUp[1], getTileX(), getTileY(), null );
if(move == 6)
g.drawImage(playerDown[1], getTileX(), getTileY(), null );
if(move == 7)
g.drawImage(playerLeft[1], getTileX(), getTileY(), null );
if(move == 8)
g.drawImage(playerRight[1], getTileX(), getTileY(), null );
}
}
This is where the map was successfully loaded. I'm not sure how i was able to make i run in accelerated graphics mode.
public class Map {
private Scanner m;
private String[] Map = new String[14]; //how many tiles in the map
private Image tiles, grass2, grass3, grass3b;
private Image wall, sand1;
private Image finish;
public Map(){
tiles = new ImageIcon("images/grass2.png").getImage();
wall = new ImageIcon("images/grass1.png").getImage();
grass2 = new ImageIcon("images/grass2.png").getImage();
grass3 = new ImageIcon("images/grass3.png").getImage();
grass3b = new ImageIcon("images/grass3b.png").getImage();
sand1 = new ImageIcon("images/sand1.png").getImage();
finish = new ImageIcon("images/tile.png").getImage();
openFile();
readFile();
closeFile();
}
public void openFile(){
try{
m = new Scanner(new File("images/Map.txt"));
}catch(Exception e){
System.out.println("Can't open the file: "+e);
}
}
public void readFile(){
while(m.hasNext()){ // read through the file
for(int i = 0; i < 14; i++){
Map[i] = m.next();
}
}
}
public void closeFile(){
m.close();
}
public String getMap(int x, int y){
String index = Map[y].substring(x, x + 1);
return index;
}
public Image getTiles(){
return tiles;
}
public Image getWall(){
return wall;
}
public Image getFinish(){
return finish;
}
public Image getImageGrass2(){
return grass2;
}
public Image getImageGrass3(){
return grass3;
}
public Image getImageGrass3b(){
return grass3b;
}
public Image getImageSand1(){
return sand1;
}
//added
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for(int y = 0; y < 14; y++){
for(int x = 0; x < 14; x++){
/**draw the finish line**/
if(getMap(x, y).equals("f")){
g2.drawImage(getFinish(), x*32,y*32, null);
}
/**-----------------------)*/
if(getMap(x, y).equals("g")){
//the size of the image is X 20 by Y20
g2.drawImage(getTiles(), x*32, y*32, null);
}
if(getMap(x, y).equals("w")){
//the size of the image is X 20 by Y20
g2.drawImage(getWall(), x*32, y*32, null);
}
if(getMap(x, y).equals("d")){
//the size of the image is X 20 by Y20
g2.drawImage(getImageGrass3(), x*32, y*32, null);
}
if(getMap(x, y).equals("b")){
//the size of the image is X 20 by Y20
g2.drawImage(getImageGrass3b(), x*32, y*32, null);
}
if(getMap(x, y).equals("s")){
//the size of the image is X 20 by Y20
g2.drawImage(getImageSand1(), x*32, y*32, null);
}
}
}
}
}

Categories