I have been having some trouble with attempting to create constantly "spawning" objects (called Rushers) that chase after a single object that is user-controlled (called Character). My main issue is the coordinates for the Rushers seem to be the exact same as that of the Character.
I have my code split into several classes. Here is the code for the Character first:
public class Gamepanel {
private boolean right = false, left = false, up = false, down = false;
public Character mainChar;
private static int xCoor = 230;
private static int yCoor = 210;
This is the main loop:
public void tick(){
mainChar = new Character(xCoor, yCoor, 30, 50);
mainChar.setxCoor(xCoor);
mainChar.setyCoor(yCoor);
if(right && mainChar.getxCoor() < 469) xCoor+=5;
if(left && mainChar.getxCoor() > 0) xCoor -= 5;
if(up && mainChar.getyCoor() > 0) yCoor -= 5;
if(down && mainChar.getyCoor() < 449) yCoor+=5;
}
The GFX:
mainChar.draw(g);
The controls are basic keyPressed and keyReleased methods. I will not post them for sake of brevity, as they seem to be working fine.
This is the code for the Character class:
public class Character {
int xCoor = 230;
int yCoor = 210;
int width = 30;
int height = 50;
public Character(int xCoor, int yCoor, int width, int height) {
this.xCoor = xCoor;
this.yCoor = yCoor;
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(xCoor, yCoor, width, height);
}
public int getxCoor() {
return xCoor;
}
public void setxCoor(int xCoor) {
this.xCoor = xCoor;
}
public int getyCoor() {
return yCoor;
}
public void setyCoor(int yCoor) {
this.yCoor = yCoor;
}
}
These all appear to work as normal with no massive issues. The biggest problems I was having was with my other objects, the Rushers. Here is their code in the Gamepanel:
public class Gamepanel {
private Rusher rusher;
ArrayList<Rusher> rushers;
int spawnTimer = 0;
public Gamepanel() {
rushers = new ArrayList <Rusher>();
}
public void tick(){
spawnTimer++;
if(spawnTimer > 75) {
spawn();
spawnTimer = 0;
}
if(rushers.size() > 0) {
for(int i = 0; i < rushers.size(); i++) {
rushers.get(i).tick();
}
}
}
The GFX:
if(rushers.size() > 0) {
for(int i = 0 ; i < rushers.size(); i++) {
rushers.get(i).draw(g);
}
}
Spawn method (pretty sure the error is in here):
public void spawn() {
int xSpawn[] = new int[4];
int ySpawn[] = new int[4];
ySpawn[0] = 250; ySpawn[1] = 499; ySpawn[2] = 250; ySpawn[3] = 0;
xSpawn[0] = 0; xSpawn[1] = 250; xSpawn[2] = 499; xSpawn[3] = 250;
int spawnCoor = randomRange(0, 3);
rusher = new Rusher(xSpawn[spawnCoor], ySpawn[spawnCoor], 10, 10);
rusher.setxCoor(xSpawn[spawnCoor]);
rusher.setyCoor(ySpawn[spawnCoor]);
rushers.add(rusher);
}
and finally, the Rusher class:
public class Rusher {
private static int xCoor;
private static int yCoor;
private int width = 20;
private int height = 20;
public Rusher(int xCoor, int yCoor, int width, int height) {
super(xCoor, yCoor, width, height);
Rusher.xCoor = xCoor;
Rusher.yCoor = yCoor;
}
public void tick() {
if(xCoor > Gamepanel.mainxCoor()) xCoor -= 2;
if(yCoor > Gamepanel.mainyCoor()) yCoor -= 2;
if(xCoor < Gamepanel.mainxCoor()) xCoor += 2;
if(yCoor < Gamepanel.mainyCoor()) yCoor += 2;
}
public void draw(Graphics g) {
g.setColor(Color.RED);
g.fillRect(xCoor, yCoor, width, height);
}
public int getxCoor() {
return xCoor;
}
public void setxCoor(int xCoor) {
Rusher.xCoor = xCoor;
}
public int getyCoor() {
return yCoor;
}
public void setyCoor(int yCoor) {
Rusher.yCoor = yCoor;
}
}
Just to recap, the main issue is that the Rushers will spawn with the same coordinates as the Character, and will also move just as fast, despite me setting their motion to 3 slower than the Character. I tried to make this as brief as possible. If more code is needed, I do have some others that relate to these objects.
Thanks in advance.
I found it out. I was setting the coordinates for the Rushers as static, so they all shared the same ones. When I changed that, and adjusted some other, smaller things, it worked out much better.
Related
I am having some issues trying to set my character to spawn in the right color spot in my map sheet in java.
In the vídeos that I am watching to learn this I have every single line code identical to the vídeo but yet my character instead of spawning in the right spot is spawning in the up middle corner of the screen.
I'm using those code lines to make him and all Tiles and Entities spawn in the right spot :
public class World {
private Tile[] tiles;
public static int WIDTH,HEIGHT;
public World(String path) {
try {
BufferedImage map = ImageIO.read(getClass().getResource(path));
int[] pixels = new int[map.getWidth() * map.getHeight()];
WIDTH = map.getWidth();
HEIGHT = map.getHeight();
tiles = new Tile[map.getWidth() * map.getHeight()];
map.getRGB(0, 0, map.getWidth(), map.getHeight(), pixels, 0, map.getWidth());
for(int xx = 0; xx < map.getWidth(); xx++) {
for(int yy = 0; yy < map.getHeight(); yy++) {
int pixelAtual = pixels[xx + (yy*map.getWidth())];
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_FLOOR);
if(pixelAtual == 0xFF000000) {
//FLOOR
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_FLOOR);
}else if(pixelAtual == 0xFFFFFFFF){
//PAREDE
tiles[xx + (yy * WIDTH)] = new FloorTile(xx*16,yy*16, Tile.TILE_WALL);
}else if(pixelAtual == 0xFF0026FF) {
//Player
Game.player.setX(xx*16);
Game.player.setY(yy*16);
}else if(pixelAtual == 0xFFFF0000){
//Enemy
}else if(pixelAtual == 0xFFFF00DC) {
//WEAPON
}else if(pixelAtual == 0xFFFF7F7F) {
//LIFEPACK
}else if(pixelAtual == 0xFFFFD800) {
//BULLET
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void render(Graphics g) {
for(int xx = 0; xx < WIDTH; xx++) {
for(int yy = 0; yy < HEIGHT; yy++) {
Tile tile = tiles[xx + (yy*WIDTH)];
tile.render(g);
}
}
}
}
But when I use these two code lines that are from my Entity Class that are suposed to make my character spawn in the right place it doesn't work at all!
Game.player.setX(xx16);
Game.player.setY(yy16);
Here's my Entity Class for you to see if i did something wrong, and again, i did everything exactely like int the vídeo an in the vídeo it worked.
public class Entity {
public static BufferedImage LIFEPACK_EN = Game.spritesheet.getSprite(78, 0, 16, 16);
public static BufferedImage WEAPON_EN = Game.spritesheet.getSprite(96, 0, 16, 16);
public static BufferedImage BULLET_EN = Game.spritesheet.getSprite(78, 16, 16, 16);
public static BufferedImage ENEMY_EN = Game.spritesheet.getSprite(96, 16, 16, 16);
protected double x;
protected double y;
protected int width;
protected int height;
private BufferedImage sprite;
public Entity(int x, int y, int width, int height, BufferedImage sprite) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.sprite = sprite;
}
public void setX(int newX) {
this.x = newX;
}
public void setY(int newY) {
this.x = newY;
}
public int getX() {
return (int)this.x;
}
public int getY() {
return (int)this.y;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public void update() {
}
public void render(Graphics g) {
g.drawImage(sprite, this.getX(), this.getY(), null);
}
}
I saw where I was wrong.
public void setY(int newY) {
this.x = newY;
In this line code here, it's suposed to be this.y and I thought that I did that, but I couldn't see.
I'm creating a 2D java game and ran into a nullpointer exception. Whenever I call my render in the playstate class, it throws the exception. I had previously rendered the Font file and got it to work when commenting out the player object references. The player "linkformatted.png" file is able to load after trying and catching, but the nullpointer exception stays. Changing the values didn't work.
public class PlayState extends GameState {
private Font font;
private Player player;
public PlayState(GameStateManager gsm) {
super(gsm);
font = new Font("font/ZeldaFont.png", 16, 16);
player = new Player(new Sprite("entity/linkformatted.png"), new Vector2f(100, 100), 32);
}
public void update() {
player.update();
}
public void input(MouseHandler mouse, KeyHandler key) {
player.input(mouse, key);
}
public void render(Graphics2D g) {
Sprite.drawArray(g, font, "YOU", new Vector2f(100, 100), 32, 32, 16, 0);
player.render(g);
}
}
public class Sprite {
private BufferedImage SPRITESHEET = null;
private BufferedImage[][] spriteArray;
private final int TILE_SIZE = 32;
public int w;
public int h;
private int wSprite;
private int hSprite;
public Sprite(String file) {
w = TILE_SIZE;
h = TILE_SIZE;
System.out.println("Loading: " + file + "...");
SPRITESHEET = loadSprite(file);
wSprite = SPRITESHEET.getWidth() / w;
hSprite = SPRITESHEET.getHeight() / h;
loadSpriteArray();
}
public Sprite(String file, int w, int h) {
this.w = w;
this.h = h;
System.out.println("Loading: " + file + "...");
SPRITESHEET = loadSprite(file);
wSprite = SPRITESHEET.getWidth() / w;
hSprite = SPRITESHEET.getHeight() / h;
loadSpriteArray();
}
public void setSize(int width, int height) {
setWidth(width);
setHeight(height);
}
public void setWidth(int i) {
w = i;
wSprite = SPRITESHEET.getWidth() / w;
}
public void setHeight(int i) {
h = i;
hSprite = SPRITESHEET.getHeight() / h;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
private BufferedImage loadSprite(String file) {
BufferedImage sprite = null;
try {
sprite = ImageIO.read(getClass().getClassLoader().getResourceAsStream(file));
} catch(Exception e) {
System.out.println("Error: could not load file: " + file);
}
return sprite;
}
public void loadSpriteArray() {
spriteArray = new BufferedImage[wSprite][hSprite];
for(int x = 0; x < wSprite; x++) {
for(int y = 0; y < hSprite; y++) {
spriteArray[x][y] = getSprite(x, y);
}
}
}
public BufferedImage getSpriteSheet() {
return SPRITESHEET;
}
public BufferedImage getSprite(int x, int y) {
return SPRITESHEET.getSubimage(x * w, y * h, w, h);
}
public BufferedImage[] getSpriteArray(int i) {
return spriteArray[i];
}
public BufferedImage[][] getSpriteArray2(int i) {
return spriteArray;
}
public static void drawArray(Graphics2D g, ArrayList<BufferedImage> img, Vector2f pos, int width, int height, int xOffset, int yOffset) {
float x = pos.x;
float y = pos.y;
for(int i = 0; i < img.size(); i++) {
if(img.get(i) != null) {
g.drawImage(img.get(i), (int) x, (int) y, width, height, null);
}
x += xOffset;
y += yOffset;
}
}
public static void drawArray(Graphics2D g, Font f, String word, Vector2f pos, int width, int height, int xOffset, int yOffset) {
float x = pos.x;
float y = pos.y;
for(int i = 0; i < word.length(); i++ ) {
if(word.charAt(i) != 32); // the space
g.drawImage(f.getFont(word.charAt(i)), (int) x, (int) y, width, height, null);
x += xOffset;
y += yOffset;
}
}
}
public class Animation {
private BufferedImage[] frames;
private int currentFrame;
private int numFrames;
private int count;
private int delay;
private int timesPlayed;
public Animation(BufferedImage[] frames) {
timesPlayed = 0;
setFrames(frames);
}
public Animation() {
timesPlayed = 0;
}
public void setFrames(BufferedImage[] frames) {
frames = frames;
currentFrame = 0;
timesPlayed = 0;
delay = 2;
numFrames = frames.length;
}
public void setDelay(int i) { delay = i;}
public void setFrame(int i) { currentFrame = i;}
public void setNumFrames(int i) { numFrames = i;}
public void update() {
if(delay == -1) return;
count++;
if(count == delay) {
currentFrame++;
count = 0;
}
if(currentFrame == numFrames) {
currentFrame = 0;
timesPlayed++;
}
}
public int getDelay() {
return delay;
}
public int getFrame() {
return currentFrame;
}
public int getCount() {
return count;
}
public BufferedImage getImage() {
return frames[currentFrame];
}
public boolean hasPlayedOnce() {
return timesPlayed > 0;
}
public boolean hasPlayed(int i) {
return timesPlayed == i;
}
}
public class Player extends Entity {
public Player(Sprite sprite, Vector2f origin, int size) {
super(sprite, origin, size);
}
public void move() {
if(up) {
dy -= acc;
if(dy < -maxSpeed) {
dy = -maxSpeed;
}
} else {
if(dy < 0) {
dy += deacc;
if(dy > 0) {
dy = 0;
}
}
}
if(down) {
dy += acc;
if(dy < maxSpeed) {
dy = maxSpeed;
}
} else {
if(dy > 0) {
dy -= deacc;
if(dy < 0) {
dy = 0;
}
}
}
if(left) {
dx -= acc;
if(dx < -maxSpeed) {
dy = -maxSpeed;
}
} else {
if(dx < 0) {
dx += deacc;
if(dx > 0) {
dx = 0;
}
}
}
if(right) {
dx += acc;
if(dx > maxSpeed) {
dy = maxSpeed;
}
} else {
if(dx > 0) {
dx -= deacc;
if(dx < 0) {
dx = 0;
}
}
}
}
public void update() {
super.update();
move();
pos.x = dx;
pos.y = dy;
}
#Override
public void render(Graphics2D g) {
g.drawImage(ani.getImage(), (int) (pos.x), (int) (pos.y), size, size, null);
}
public void input(MouseHandler mouse, KeyHandler key) {
if(key.up.down) {
up = true;
} else {
up = false;
}
if(key.down.down) {
down = true;
} else {
down = false;
}
if(key.left.down) {
left = true;
} else {
left = false;
}
if(key.right.down) {
right = true;
} else {
right = false;
}
if(key.attack.down) {
attack = true;
} else {
attack = false;
}
}
}
Here is what is printed:
Loading: entity/linkformatted.png...
Exception in thread "GameThread" java.lang.NullPointerException
at com.zwellis.game.graphics.Animation.getImage(Animation.java:62)
at com.zwellis.game.entity.Player.render(Player.java:82)
at com.zwellis.game.states.PlayState.render(PlayState.java:34)
at com.zwellis.game.states.GameStateManager.render(GameStateManager.java:71)
at com.zwellis.game.GamePanel.render(GamePanel.java:133)
at com.zwellis.game.GamePanel.run(GamePanel.java:90)
at java.base/java.lang.Thread.run(Thread.java:834)
Here is what happens when I made another file to display the image:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "entity/linkformatted.png";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
Here is what happens:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at ImageInFrame.main(ImageInFrame.java:11)
Here is also the github link
https://github.com/xfyktcl/ZwellisKnight.git
Whenever I tell the rectangle to go left, it moves al the way to the left side of the screen when I only want it to move a little bit. And whenever I tell it to move right, it wont move at all. What am I doing wrong?
public class Balls {
private static final int MOVE_SPEED_X = 2;
private int x, y, width, height, velX, velY;
private Rectangle rect;
public Balls(int x, int y, int height, int width) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
velX = 0;
}
public void update() {
y += 3;
}
public void reset() {
y = 0;
}
public void accelLeft() {
x = -MOVE_SPEED_X;
}
public void accelRight() {
x = +MOVE_SPEED_X;
}
}
Second Block of relevant code
public class PlayState extends State {
private Paddle paddleRight, paddleLeft;
private static final int PADDLE_WIDTH = 30;
private static final int PADDLE_HEIGHT = 60;
private Ball ball;
private Balls balls;
// bDiam stands for ball diameter
private static int bDiam = 30;
private int playerScore = 0;
private Font scoreFont;
#Override
public void init() {
paddleLeft = new Paddle(0, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
paddleRight = new Paddle(785, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
scoreFont = new Font("SansSerif", Font.BOLD, 25);
//ball = new Ball(300, 200, bDiam, bDiam);
balls = new Balls(500, 0, bDiam, bDiam);
}
#Override
public void onClick(MouseEvent e) {
// bDiam = bDiam + 20;
}
#Override
public void update() {
balls.update();
if (balls.getY() > GameMain.GAME_HEIGHT) {
balls.reset();
}
}
#Override
public void onKeyPress (KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
balls.accelRight();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
balls.accelLeft();
}
}
}
In accelLeft it should be x = x - MOVE_SPEED_X (and similar in accelRight)
I am making a basic tile game. In my game, when the player clicks the space key, a fireball is created. However, the fireball is not fully created until the player pressed another key. In other words, if the player pressed the space key wile holding say, D, the fireball will hover over their body until they click another key or release the D key.
I have used test code in the fireball class to see that the class is initialized , however the values being passed into it are not done updating until the KeyListener is updated (I think). Why is this and how do I fix it? I just want it to be so that the second the space key is clicked the fireball is created.
The Player class:
public class Player extends MapObject{
//player stuff
private double health;
private int maxHealth;
private double mana;
private int maxMana;
private int level;
private boolean alive;
private Rectangle boundingBox;
private int direction;
private ArrayList<Integer>keyPressed;
//fireball stuff
private boolean firing; //used to make sure player only used one attack at a time;
private boolean fireAttack; //used to limit fire speed
private int fireCost;
private int fireDamage;
private ArrayList<FireBall> fireBall;
private FireBall fireball;
public Player() {
x = GamePanel.WIDTH / 2.1;
y = GamePanel.HEIGHT / 2.2;
width = 16;
height = 16;
boundingBox = new Rectangle ((int)x, (int)y, width, height);
moveSpeed = 4;
direction = 0;
keyPressed = new ArrayList<Integer>();
level = 1;
maxHealth = level * 100;
maxMana = level * 85;
fireDamage = level * 5;
fireBall = new ArrayList<FireBall>();
init();
}
public void init() {
health = maxHealth;
mana = maxMana;
alive = true;
firing = false;
fireAttack = true;
fireCost = 10;
}
public void draw(Graphics2D g) {
g.drawImage(Assets.player, (int)x, (int)y, null);
}
public void update() {
if(health == 0)
alive = false;
mana = mana + 0.04;
health = health + 0.015;
if(mana >= maxMana)
mana = maxMana;
if(health >= maxHealth)
health = maxHealth;
if(keyPressed.contains(KeyEvent.VK_W))
direction = 0;
if(keyPressed.contains(KeyEvent.VK_D))
direction = 2;
if(keyPressed.contains(KeyEvent.VK_A))
direction = 1;
if(keyPressed.contains(KeyEvent.VK_S))
direction = 3;
}
public void keyPressed(int k) {
if(k == KeyEvent.VK_SPACE) {
if(fireAttack) {
if(mana >= fireCost) {
mana -= fireCost;
fireball = new FireBall(x, y, direction);
fireBall.add(fireball);
fireAttack = false;
}
}
}
if(!keyPressed.contains(k)) keyPressed.add((k));
for(int i = 0; i < fireBall.size(); i++) {
fireBall.get(i).keyPressed(k);
}
}
public void keyReleased(int k) {
keyPressed.remove(new Integer(k));
if(k == KeyEvent.VK_SPACE)
fireAttack = true;
for(int i = 0; i < fireBall.size(); i++) {
fireBall.get(i).keyReleased(k);
}
}
the fireball class:
public class FireBall extends MapObject{
private double x, y;
private double movespeed, velX, velY;
private int direction;
private double xOffset, yOffset;
private boolean oUp = true, oDown = true, oLeft = true, oRight = true;
public void setoUp(boolean oUp) {
this.oUp = oUp;
}
public void setoDown(boolean oDown) {
this.oDown = oDown;
}
public void setoLeft(boolean oLeft) {
this.oLeft = oLeft;
}
public void setoRight(boolean oRight) {
this.oRight = oRight;
}
private ArrayList<Integer>keyPressed;
private Rectangle boundingBox;
private int fireCost;
private int fireDamage;
private boolean delete = false;
public FireBall(double x, double y, int direction) {
this.x = x; //default positions at player location
this.y = y;
movespeed = 4;
this.direction = direction;
xOffset = 0;
yOffset = 0;
width = Assets.fireball1.getWidth();
height = Assets.fireball1.getHeight();
boundingBox = new Rectangle((int)this.x, (int)this.y, width, height);
keyPressed = new ArrayList<Integer>();
}
public void update() {
x = xOffset + 150;
//xOffset += velX; note: this was commented out as part of my testing. Without
//the fireball moving it is obvious that if follows the
//player at first.
y = yOffset + 100;
//yOffset += velY;
boundingBox.x = (int)x;
boundingBox.y = (int)y;
switch(direction) {
case 0: velY = -movespeed;
velX = 0;
break;
case 1: velY = 0;
velX = -movespeed;
break;
case 2: velY = 0;
velX = movespeed;
break;
case 3: velY = movespeed;
velX = 0;
break;
}
movement();
}
public void draw(Graphics2D g) {
g.drawImage(Assets.fireball1, (int)x, (int)y, null);
}
public void keyPressed(int k) {
if(!keyPressed.contains(k)) keyPressed.add((k));
}
public void movement() {
if(keyPressed.contains(KeyEvent.VK_W) && oUp == true) {
yOffset = yOffset + 2; //PUT IN PLAYER MOVEPSEED MAY NEED TO BE CHANGED LATER
}
if(keyPressed.contains(KeyEvent.VK_D) && oRight == true) {
xOffset = xOffset -2;
}
if(keyPressed.contains(KeyEvent.VK_A) && oLeft == true) {
xOffset = xOffset + 2;
}
if(keyPressed.contains(KeyEvent.VK_S) && oDown == true) {
yOffset = yOffset - 2;
}
}
public void keyReleased(int k) {
keyPressed.remove(new Integer(k));
}
Thank you very much for any assistance you can provide!
Have you tried putting all of the stuff from keyPressed(int keyEvent) into keyTyped(int keyEvent)? Technically, a key is pressed whenever, but typing a key is both pressing and lifting your finger from it.
That may help you. Best of luck!Side note: what you are doing with those keys is very strange. Why is your class not implementing the KeyListener interface?
Im currently am working on a game in Java that spawns blocks on the top of the screen and they fall down (you have to dodge them). Currently I have the game spawning blocks on the top of the screen from an array but I do not know how to make their y position go down by (int).
Basically I just need help making a public void that checks an object array and with every instance of a object it finds it drops the y position of it by 12.
Selected snippits from code:
static Object[][] food = new Object[7][700];
public void draw() {
try {
Graphics g = bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, this.getSize().width, this.getSize().height);
// Draw to back buffer
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
g.setColor(Color.BLUE);
g.fillRect(Player.getX(), Player.getY(), Player.WIDTH, Player.HEIGHT);
g.setColor(Color.GRAY);
for(int x = 0; x < food.length; x++) {
for(int y = 0; y < food[x].length; y ++) {
Object o = food[x][y];
if(o instanceof Hamburger) {
new Hamburger(x * 100, y, g);
}
else if(o instanceof Salad) {
new Salad(x * 100, y, g);
}
}
}
GUI.draw(g);
} catch(Exception e) {
e.printStackTrace();
} finally {
bufferGraphics.dispose();
}
}
public void dropBlocks() {
}
public void addBlock() {
if(new Random().nextInt(2) == 1) {
food[new Random().nextInt(7)][0] = new Hamburger(0, 0);
} else food[new Random().nextInt(7)][0] = new Salad(0, 0);
}
public void drawBackbufferToScreen() {
bufferStrategy.show();
Toolkit.getDefaultToolkit().sync();
}
public void run() {
int i = 0;
while(running) {
i++;
draw();
Player.update();
drawBackbufferToScreen();
if(i == 50) {
addBlock();
i = 0;
}
dropBlocks();
Thread.currentThread();
try {
Thread.sleep(10);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Food.java (What Hamburger and Salad extend)
public class Food {
public static int x;
public static int y;
public static int HEIGHT;
public static int WIDTH;
public int type;
private static Image blockImage;
// Default constructor
public Food() {
Food.x = 0;
Food.y = 0;
Food.HEIGHT = 80;
Food.WIDTH = 80;
}
public Food(int x, int y) {
Food.x = x;
Food.y = y;
Food.HEIGHT = 80;
Food.WIDTH = 80;
}
// Getters and setters
I would do something like this:
Object[][] board = new Object[7][700]; //Game board.
//you can also switch the width and height
//Initialization
for (int x = 699; x >= 0; x--) {
for (int y = 0; y < 7; y++) {
if (x == 699) {
board[y][x] = BLANK; //set spot to open if it is the bottom row
continue;
}
board[y][x+1] = board[y][x]; //move row down
}
}
//Generate new Objects if needed for the top row of the board.
Clearly Object does not have a getY() method. You could do ugly things with casting and instanceof, but this design is rather putrid. Try moving towards an object oriented model.
interface Drawable {
int getX();
int getY();
void moveDown(int numSpaces);
}
class Hamburger implements Drawable {
private int x;
private int y;
public Hamburger(final int xPos, final int yPos) {
x = xPos;
y = yPos;
}
#Override
public void moveDown(final int numSpaces) {
// eg negative number, off the screen
if(isValid(numSpaces)) {
setY(getY() - numSpaces);
}
}
}
class Positioner {
public static void moveMyObjects(final Drawable[][] objs) {
for(Drawable[] rows : objs) {
for(Drawable col : rows) {
// clearly Object doesn't have a getY() method, so you should create your own interface and implement it
col.moveDown(12);
}
}
}
}