Java game Mouse input on buttons not working - java

I'm trying to make mouse input work in my Java game, but i can't seem to figure it out. I want to click where i made my button and it should change my State from End to Game and respawn my player and my bullet enemies. Why does the following code not change my State to Game instead of End?
My End Class
package BullHellSpel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import BullHellSpel.Game.STATE;
public class End extends MouseAdapter{
private Game game;
private Handler handler;
private HUD hud;
private Random r = new Random();
public End(Game game, Handler handler, HUD hud){
this.game = game;
this.handler = handler;
this.hud = hud;
}
public void mouseClicked(MouseEvent e){
int mx = e.getX();
int my = e.getY();
if(game.gameState == STATE.End){
if(mouseOver(mx, my, 75, 100, 200, 70)){
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH, Game.HEIGHT, ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
}
public void mouseReleased(MouseEvent e){
}
private boolean mouseOver(int mx, int my, int x, int y, int width, int height){
if(mx < x && mx > x + width){
if(my < y && my > y + height){
return true;
}else return false;
}else return false;
}
public void tick() {
}
public void render(Graphics g) {
Font fnt = new Font("arial", 1, 20);
Font fnt1 = new Font("arial", 1, 16);
g.setColor(Color.white);
g.setFont(fnt);
g.drawString("You lost with a score of: " + hud.getScore(), 40, 50);
g.setFont(fnt1);
g.drawRect(75, 100, 200, 70);
g.drawString("Retry Game", 90, 140);
g.drawRect(75, 215, 200, 70);
g.drawString("Quit Game", 90, 255);
}
}
In my game Class:
package BullHellSpel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import sun.applet.Main;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import java.util.Random;
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 360, HEIGHT = 640 / 1;
private boolean running = false;
private Thread thread;
private Random r;
private Handler handler;
private HUD hud;
private Spawn spawner;
private End end;
private Menu menu;
public enum STATE {
End,
Menu,
Game;
};
public STATE gameState = STATE.Game;
public Game(){
handler = new Handler();
hud = new HUD();
end = new End(this, handler, hud);
menu = new Menu(this, handler, hud);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(end);
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Space dodgers", this);
spawner = new Spawn(handler, hud);
r = new Random();
if(gameState == STATE.Game){
handler.addObject(new Player(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run()
{
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick(){
handler.tick();
if(gameState == STATE.Game)
{
hud.tick();
spawner.tick();
if(HUD.HEALTH <= 0){
HUD.HEALTH = 100;
handler.object.clear();
gameState = STATE.End;
}
}else if(gameState == STATE.End){
end.tick();
}else if(gameState == STATE.Menu){
menu.tick();
}
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//HIER KAN JE SHIT TEKENEN
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
//g.drawImage(bg, 0, 0, this);
handler.render(g);
if(gameState == STATE.Game)
{
hud.render(g);
}else if(gameState == STATE.End){
end.render(g);
}else if(gameState == STATE.Menu){
menu.render(g);
}
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max){
if(var >= max)
return var = max;
else if(var <= min)
return var = min;
else
return var;
}
public static void main(String args[]){
new Game();
}
}

Related

Changing Sprite When You Press a key

I have a sprite sheet that I can change the little slimey's picture from but it only changes like the actual image I want to make them so when I press the right key it takes the pictures and gives it the one where it's facing right. I tried to get it so that it takes a int from the slime's class and uses it when I press right but it only prints the number 2 in the console but isn't changing the picture....... the stuff for the slime....
package com.maprildoll.main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Slimey extends DollObject{
Random r = new Random();
private int x;
private int y;
public int sprites = 0;
private BufferedImage slimey;
public SpriteSheet slimes;
public Slimey(ID id, int x, int y, Slimeball slimeball) {
super(x, y, id);
this.x = x;
this.y = y;
SpriteSheet slimes = new SpriteSheet(slimeball.getSpriteSheet());
slimey = slimes.grabImage(1, 1, 69, 49);
if(sprites == 2) {
slimey = slimes.grabImage(2, 1, 69, 49);
}
}
public void tick() {
x += speedX;
y += speedY;
x = Slimeball.clamp(x, 0, Slimeball.WIDTH - 82);
y = Slimeball.clamp(y, 88, Slimeball.HEIGHT - 278);
}
public void render(Graphics g) {
g.drawImage(slimey, (int)x, (int)y, null);
}
}
the main window thingy....
package com.maprildoll.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
public class Slimeball extends Canvas implements Runnable{
private static final long serialVersionUID = -2882786666891858852L;
public static final int WIDTH = 1700, HEIGHT = 900;
private Thread thread;
private boolean running = false;
private Random r;
private Handler handler;
private BufferedImage spriteSheetSlimes;
private BufferedImage spriteSheetItem = null;
private BufferedImage items;
private Slimey slimey;
public Slimeball (Slimeball slimeball){
handler = new Handler();
this.addMouseListener(new Mousey(handler));
new Windows(WIDTH, HEIGHT, "Slimeballin' >.<!!", this);
r = new Random();
handler.addObject(new Slimeyball(WIDTH/2-32, HEIGHT/2+186, ID.Slimeyball));
}
public void init() {
requestFocus();
ImageLoader loader = new ImageLoader();
try {
spriteSheetItem = loader.loadImage("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\itemsheet.png");
spriteSheetSlimes = loader.loadImage("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\slimebox.png");
}catch(IOException e) {
e.printStackTrace();
}
addKeyListener(new Slimekey(this));
SpriteSheetTew itemsheet = new SpriteSheetTew(spriteSheetItem);
items = itemsheet.grabImage(1, 1, 32, 32);
slimey = new Slimey(ID.Slime, 1040, 620, this);
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
init();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1) {
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
private void tick() {
handler.tick();
slimey.tick();
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Color cyanie = new Color (231, 255, 254);
g.setColor(cyanie);
g.fillRect(0, 0, WIDTH, HEIGHT);
final ImageIcon background = new ImageIcon("C:\\Users\\SPooKykun\\eclipse-workspace\\MaprilDolly\\src\\com\\maprildoll\\main\\Slimeball\\testbackground.gif");
Image imgback = background.getImage();
g.drawImage(imgback, 0, 0, this);
g.drawImage(items, 865, 636, this);
slimey.render(g);
handler.render(g);
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
slimey.setSpeedX(-5);
} else if (key == KeyEvent.VK_RIGHT) {
slimey.setSpeedX(+5);
slimey.sprites = 2;
System.out.println(slimey.sprites);
} else if (key == KeyEvent.VK_ALT){
slimey.setSpeedY(-8);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
slimey.setSpeedX(0);
} else if (key == KeyEvent.VK_RIGHT) {
slimey.setSpeedX(0);
} else if (key == KeyEvent.VK_ALT);{
slimey.setSpeedY(+4);
}
}
public static int clamp(double x, int min, int max){
if(x >= max)
return (int) (x = max);
else if(x <= min)
return (int) (x = min);
else
return (int) x;
}
public BufferedImage getSpriteSheet() {
return spriteSheetSlimes;
}
}
I tried to put a keylistener to the Slimey but for some reason the keyboard would never work when it was in there..... soo how would I take a image from the sheet and add it to the keypressed stuff I want to put the right facing one when it presses right.....

Java Graphics NullPointerException When The Exact Same Thing Works Somewhere Else

I'm currently making a simple game with java Graphics and using multiple menus as well. Such as Help, Main, the Game itself, Lose, and Win. All menus have their own render functions that are called depending on the state of the game. All of the menus work, except for the 'Win' menu. There is the 'Lose' and the 'Win' menu both posted. They're pretty much the same thing but 'Win' will not work.
Render in main game:
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(GameState == STATE.Game) {
handler.render(g);
hud.render(g);
} else if(GameState == STATE.Menu) {
menu.render(g);
} else if(GameState == STATE.Help) {
help.render(g);
} else if(GameState == STATE.EndMenu) {
endMenu.render(g);
} else if(GameState == STATE.Win) {
win.render(g);
}
g.dispose();
bs.show();
}
Win:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
public class Win {
public Win(){}
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("SansSerriff", Font.BOLD, 100));
g.drawString("YOU WIN!!!", Game.WIDTH/2 - 280, Game.HEIGHT/2 - 50);
g.setFont(new Font("SansSerriff", Font.PLAIN, 60));
g.drawString("Player Again", 360, 600);
g.drawRect(250, 535, 500, 100);
}
}
Lose:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
public class EndMenu {
public EndMenu() {}
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("SansSerriff", Font.BOLD, 100));
g.drawString("YOU LOSE!!", Game.WIDTH/2 - 280, Game.HEIGHT/2 - 50);
g.setFont(new Font("SansSerriff", Font.PLAIN, 60));
g.drawString("Play Again", 360, 600);
g.drawRect(250, 535, 500, 100);
}
}
Error Message:
Exception in thread "Thread-2" java.lang.NullPointerException
at Main.Game.render(Game.java:132)
at Main.Game.run(Game.java:86)
at java.lang.Thread.run(Unknown Source)
All help is greatly appreciated. Thank you!
EDIT
Game:
package Main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 2287623113957789623L;
public static final int WIDTH = 1000, HEIGHT = WIDTH/12 * 9;
private Thread thread;
public static boolean running = false;
private Handler handler;
private HUD hud;
private Spawner spawner;
private Menu menu;
private Help help;
private EndMenu endMenu;
private Win win;
public static STATE GameState = STATE.Win;
//----------Game()----------//
//---------------------------------------------------------------------------
public Game() {
handler = new Handler();
menu = new Menu(this, handler);
help = new Help();
endMenu = new EndMenu();
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Wave", this);
hud = new HUD();
spawner = new Spawner(handler, hud);
}
//----------Game Modes----------//
//---------------------------------------------------------------------------
public enum STATE {
Menu,
Game,
Help,
EndMenu,
Win,
}
//----------start()----------//
//---------------------------------------------------------------------------
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
//----------stop()----------//
//---------------------------------------------------------------------------
public synchronized void stop() {
try {
thread.join();
running = false;
}catch(Exception e) {
e.printStackTrace();
}
}
//----------run()-----------//
//---------------------------------------------------------------------------
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
//----------tick()----------//
//---------------------------------------------------------------------------
private void tick() {
if(GameState == STATE.Game) {
handler.tick();
hud.tick();
spawner.tick();
}
if(HUD.HEALTH <= 0 && HUD.HEALTH2 <= 0) {
GameState = STATE.EndMenu;
}
}
//----------render()----------//
//---------------------------------------------------------------------------
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(GameState == STATE.Game) {
handler.render(g);
hud.render(g);
} else if(GameState == STATE.Menu) {
menu.render(g);
} else if(GameState == STATE.Help) {
help.render(g);
} else if(GameState == STATE.EndMenu) {
endMenu.render(g);
} else if(GameState == STATE.Win) {
win.render(g);
}
g.dispose();
bs.show();
}
//----------clamp()----------//
//--------------------------------------------------------------------------
public static float clamp(float var, float min, float max) {
if(var >= max)
return var = max;
else if(var < min)
return var = min;
else
return var;
}
//----------main()----------//
//--------------------------------------------------------------------------
public static void main(String args[]) {
new Game();
}
}
Game.java.132: win.render(g);
Game.java.86: render();
You're getting an NPE on this line:
win.render(g);
because win is null. You've defined it, but haven't assigned a value to it.
Based on your code, you should update your Game constructor to include the following line:
win = new Win();

Sprite not moving properly Java

I am trying to make a Space Shooter using java, but it isn't working. I am currently working on spawning the enemies. To hold the positions of all the enemies, I used an ArrayList called allEnemies. The ArrayList is filled with Point objects. I am updating the Game by calling updateEnemies() in my game loop.
Originally, I had the enemy's y position increment by 1, but that was too fast, so I changed it to 0.2 in an attempt to slow it down. Once I made it 0.2, the sprites spawned at the top but didn't move down. I works for any value above 1, including decimals, but not anything below. Here is my code:
Enemy.java
package main;
import java.awt.Point;
import java.util.ArrayList;
public class Enemy {
static ArrayList<Point> allEnemies = new ArrayList<Point>();
public static ArrayList<Point> createEnemies(int round) {
for (int i = 0; i < round; i++) {
Point newEnemyLocation = new Point((int) (Math.random()*Game.WIDTH - 64), 0);
allEnemies.add(newEnemyLocation);
}
return allEnemies;
}
public static ArrayList<Point> updateEnemies() {
if (allEnemies.size() != 0) {
for (int i = 0; i < allEnemies.size(); i++) {
Point enemyLocation = allEnemies.get(i);
if (enemyLocation.y <= Game.HEIGHT) {
allEnemies.get(i).y += 0.2;
} else {
allEnemies.remove(i);
}
}
}
return allEnemies;
}
}
Game.java
package main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener {
//declare values
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Space Shooter";
private boolean running = false;
private Thread thread;
private Player player;
private BufferedImage playerImage;
private BufferedImage bulletImage;
private BufferedImage enemyImage;
int playerx;
int playery;
int round = 1;
public Game() {
//
player = new Player((WIDTH/2)-32, HEIGHT-200);
//allocates all file resources
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/enemy.png"));
} catch (IOException e) {
e.printStackTrace();
}
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
//starts thread
private synchronized void start() {
if (running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
//stops thread
private synchronized void stop() {
if (!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
#Override
//game loop
public void run() {
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta > 1) {
tick();
updates++;
delta--;
}
Shoot.updateBullets();
Enemy.updateEnemies();
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " TICKS, " + frames + " FPS");
updates = 0;
frames = 0;
}
}
stop();
}
//updates sprite locations
public void tick() {
playerx = player.getX();
playery = player.getY();
}
//renders sprites
public void render() {
//setting up triple-buffering
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//////////////////////////////////
g.setColor(Color.BLACK); g.fillRect(0,0,getWidth(), getHeight());
g.drawImage(playerImage, playerx, playery, this);
if (Shoot.allBullets.size() != 0) {
for (int i = 0; i < Shoot.allBullets.size(); i++) {
int bulletx = (int) Shoot.allBullets.get(i).getX();
int bullety = (int) Shoot.allBullets.get(i).getY();
g.drawImage(bulletImage, bulletx + 21, bullety, this);
}
}
if (Enemy.allEnemies.size() != 0) {
for (int i = 0; i < Enemy.allEnemies.size(); i++) {
int enemyx = (int) Enemy.allEnemies.get(i).getX();
int enemyy = (int) Enemy.allEnemies.get(i).getY();
g.drawImage(enemyImage, enemyx, enemyy, this);
}
} else {
Enemy.createEnemies(round);
round++;
}
//////////////////////////////////
g.dispose();
bs.show();
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
Shoot.addBullet(player.getX(), player.getY());
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
player.setY(playery -= 20);
} else if (key == KeyEvent.VK_DOWN) {
player.setY(playery += 20);
} else if (key == KeyEvent.VK_RIGHT) {
player.setX(playerx += 20);
} else if (key == KeyEvent.VK_LEFT) {
player.setX(playerx -= 20);
}
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
game.start();
}
}
Hello it is because the point class holds 2 integers x and y and you are trying to add 0.2 to a integer that only can store values without decimals so you have 2 options 1 is to change the point to a Point2D (holds doubles and a double can hold numbers with decimals) or you could create a enemy class with a x and y float/double but in this case I would go for option 1 because this is a small game, good luck!
Edit:
I was wrong about point2d, just saw that it is a abstract class so do like this
public class Enemy{
public double x,y;
Public Enemy(double x, double y){
this.x = x;
this.y = y;
}
}
And use that as the object in your arraylist

Make my circles randomly disappear and after random seconds again appear

So I'm making very simple game. Game is about some guy who jumps on rocks(circles) and rocks sometimes get covered by water and when they are, you cant stand on them otherwise you'll fall into water and drown. I'm stuck in part where i need to make those rocks disappear(be covered by water). So I need at randomized time make them disappear, for random seconds(not too long) make them "invisible" and then again they need to show up. I'm still kinda beginner and I would appreciate any kind of answer but if you could explain it to me I'd be thrilled.
Here is my code:
My main class
package com.pitcher654.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.util.Random;
import com.pitcher654.main.Game.STATE;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = -7800496711589684767L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Random r;
private Handler handler;
//private HUD hud;
private Menu menu;
public enum STATE {
Menu,
Help,
Game
};
public STATE gameState = STATE.Menu;
public Game() {
handler = new Handler();
menu = new Menu(this, handler);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "My game", this);
//hud = new HUD();
r = new Random();
if(gameState == STATE.Game) {
//handler.addObject(new Player(100, 200, ID.Player));
}
//handler.addObject(new Player(100, 200, ID.Player));
//handler.addObject(new BasicEnemy(100, 200, ID.BasicEnemy));
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try {
thread.join();
running = false;
}catch(Exception ex) { ex.printStackTrace(); }
}
public void run()
{
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
//System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick() {
handler.tick();
//hud.tick();
if(gameState == STATE.Game) {
}else if(gameState == STATE.Menu) {
menu.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, WIDTH, HEIGHT);
if(gameState == STATE.Game) {
g.setColor(new Color(209, 155, 29));
for(int i = 0; i < 5; i++) {
g.fillOval(80 + (100 * i), 325, 70, 20);
}
}else if(gameState == STATE.Menu || gameState == STATE.Help){
menu.render(g);
}
handler.render(g);
if(gameState == STATE.Game) {
}
//hud.render(g);
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max) {
if(var >= max)
return var = max;
else if(var <= max)
return var = min;
else
return var;
}
public static void main(String[] args) {
new Game();
}
}
My Player class where I create my player:
package com.pitcher654.main;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import com.pitcher654.main.Game.STATE;
public class Player extends GameObject {
Random r = new Random();
public Player(int x, int y, ID id) {
super(x, y, id);
//velX = r.nextInt(5) + 1;
//velY = r.nextInt(5);
}
public void tick() {
x += velX;
y += velY;
//System.out.println(x);
if(x == 500) x = 500;
}
public void render(Graphics g) {
if(id == ID.Player) g.setColor(Color.white);
if(id == ID.Player2) g.setColor(Color.blue);
g.fillRect(x, y, 32, 32);
g.drawLine(x + 15, y, x + 15, y + 100);
g.drawLine(x + 15, y + 100, x, y + 135);
g.drawLine(x + 15, y + 100, x + 33, y + 135);
g.drawLine(x + 15, y + 70, x - 35, y + 30);
g.drawLine(x + 15, y + 70, x + 65, y + 30);
/*if(game.gameState == STATE.Menu) {
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
}*/
}
}
And my game Object class:
package com.pitcher654.main;
import java.awt.Graphics;
public abstract class GameObject {
protected static int x, y;
protected ID id;
protected int velX, velY;
public GameObject(int x, int y, ID id) {
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick();
public abstract void render(Graphics g);
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setID(ID id) {
this.id = id;
}
public ID getID() {
return id;
}
public void setVelX(int velX) {
this.velX = velX;
}
public void setVelY(int velY) {
this.velY = velY;
}
public int getVelX() {
return velX;
}
public int getVelY() {
return velY;
}
}
If you need any other class, just tell me I'll post it.
You should store a status of every stone in the game.
So if you have given number of stones (5), create a constant field with this number. Then create an array of ### boolean values where you'll save status of each stone.
Then create an array of "times" when the stones will change their visibility.
private static final int NUM_STONES = 5; // you can change the # of the stones here
private boolean[] visible = new int[NUM_STONES];
private long[] changeTimes = new long[NUM_STONES];
In your game's init method initialize the values.
for(int i=0; i<NUM_STONES; i++){
visible[i] = true; // each stone will be visible
changeTimes[i] = System.currentTimeMillis() + r.nextInt(10000); // every stone will disappear in less than 10 seconds
}
In your update method (I suppose tick() ) update visibility statuses.
long now = System.currentTimeMillis();
for(int i=0; i<NUM_STONES; i++){
if(now < changeTimes[i]){ // if the time has come
if(visible[i]) changeTimes[i] = now + r.nextInt(5000); // every stone will be invisible up to five seconds
else changeTimes[i] = now + r.nextInt(10000); // every stone will be visible again up to 10 seconds
visible[i] = !visible[i]; // switch the visibility state
}
}
And finally add the condition to the render method:
if(gameState == STATE.Game) {
for(int i = 0; i < NUM_STONES; i++) {
if(visible[i] g.setColor(new Color(209, 155, 29));
else g.setColor(new Color(107, 155, 170));
g.fillOval(80 + (100 * i), 325, 70, 20);
}
}
That should be it.
Next thing you should do is extracting magic numbers into constants, like I showed you with the NUM_STONES. And also don't create a new instance of the Color class every time you render a stone and create instances of the colors just like I've written before.
Also notice that some stones will disappear (and appear again) for a very short time - you can add few seconds to the changeTimes[i] in your update method to ensure that each stone will be (in)visible at least for this amount of time.

Java Game - unknown error

I have an error it everytime I try to start it, it comes up with a blank window and these error messages.
Exception in thread "Thread-2" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red Green
at java.awt.Color.testColorValueRange(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at com.tutorial.main.HUD.render(HUD.java:32)
at com.tutorial.main.Game.render(Game.java:118)
at com.tutorial.main.Game.run(Game.java:85)
at java.lang.Thread.run(Unknown Source)
I have a suspicion it is something to do with rendering but not sure can someone help.
I have inserted the following codes:
Game
Window
SmartEnemy
HUD
ID
Handler
package com.tutorial.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 7580815534084638412L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = true;
private Random r;
private Handler handler;
private HUD hud;
private Spawn spawner;
public Game() {
new Window(WIDTH, HEIGHT, "Lets Build a Game!", this);
handler = new Handler();
hud = new HUD();
spawner = new Spawn(handler, hud);
this.addKeyListener(new KeyInput(handler));
r = new Random();
// for(int i = 0; i <1; i++){
//implementing Player1
handler.addObject(new Player(WIDTH / 2 - 32, HEIGHT / 2 - 32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH), r.nextInt(Game.HEIGHT), ID.BasicEnemy, handler));
//implementing Player2
//handler.addObject(new Player(WIDTH/2-32, HEIGHT/2+64, ID.Player2));
/*for (int i = 0; i < 1; i++){
//implementing BasicEnemy
handler.addObject(new BasicEnemy(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.BasicEnemy, handler));
}*/
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
try {
thread.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if (running) {
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
//System.out.println("FPS: " + frames);
frames = 0;
}
}
}
}
private void tick() {
handler.tick();
hud.tick();
spawner.tick();
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
hud.render(g);
g.dispose();
bs.show();
}
public static float clamp(float
var, float min, float max) {
if (var >= max) {
return var = max;
} else if (var <= min) {
return var = min;
} else {
return var;
}
}
public static void main(String args[]) {
Game game = new Game();
game.start();
}
}
package com.tutorial.main;
import java.awt.Canvas;
import javax.swing.*;
import java.awt.Dimension;
public class Window extends Canvas {
private static final long serialVersionUID = -240840600533728354L;
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setVisible(true);
}
}
package com.tutorial.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class SmartEnemy extends GameObject{
private Handler handler;
private GameObject player;
public SmartEnemy(int x, int y, ID id, Handler handler) {
super(x, y, id);
this.handler = handler;
for(int i = 0; i < handler.object.size(); i++){
if(handler.object.get(i).getId() == ID.Player) player = handler.object.get(i);
}
}
public Rectangle getBounds(){
return new Rectangle((int)x, (int)y, 32, 32);
}
public void tick() {
handler.addObject(new Trail(x, y,ID.Trail, Color.GREEN, 16, 16, 0.02f, handler));
x += velX;
y += velY;
float diffX = x - player.getX() - 8;
float diffY = y - player.getY() - 8;
float distance = (float) Math.sqrt((x - player.getX()) * (x - player.getX()) + (y - player.getY()) * (y - player.getY()));
velX = (float) ((-1.0/distance) * diffX);
velY = (float) ((-1.0/distance) * diffY);
if (y <= 0 || y >= Game.HEIGHT - 37) velY *= -1;
if (x <= 0 || x >= Game.WIDTH - 16) velX*= -1;
}
public void render(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect((int)x, (int)y, 16, 16);
}
}
package com.tutorial.main;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler {
LinkedList < GameObject > object = new LinkedList < GameObject > ();
public void tick() {
for (int i = 0; i < object.size(); i++) {
GameObject tempObject = object.get(i);
tempObject.tick();
}
};
public void render(Graphics g) {
for (int i = 0; i < object.size(); i++) {
GameObject tempObject = object.get(i);
tempObject.render(g);
}
}
public void addObject(GameObject object) {
this.object.add(object);
}
public void removeObject(GameObject object) {
this.object.remove(object);
}
}
package com.tutorial.main;
import java.awt.Color;
import java.awt.Graphics;
public class HUD {
public static float HEALTH = 100;
private float greenValue = 255;
private int level = 1;
private float score = 0;
public void tick(){
HEALTH = Game.clamp(HEALTH, 0, 100);
greenValue = Game.clamp(greenValue, 0, 255);
greenValue = HEALTH*2;
score++;
}
public void render(Graphics g){
//Background for Health bar
g.setColor(Color.gray);
g.fillRect(15, 15, 200, 32);
//Health Bar
g.setColor(new Color(75, (float) greenValue, 0));
g.fillRect(15, 15, (int) (HEALTH * 2), 32);
g.setColor(Color.WHITE);
g.drawRect(15, 15, 200, 32);
g.drawString("Score: " + score, 15, 60);
g.drawString("Level: " + level, 15, 75);
}
/*int level = 1, point = 0;
//point scoring system
for(int i = 2; i > 1; i++){
if(HEALTH > 0){
point++;
System.out.println(point);
}
}
}*/
private void score(float score){
this.score = score;
}
public float getScore(){
return score;
}
public int getLevel(){
return level;
}
public void setLevel(int level){
this.level = level;
}
}
package com.tutorial.main;
import java.awt.Graphics;
import java.awt.Rectangle;
public abstract class GameObject {
protected float x, y;
protected ID id;
protected float velX, velY;
public GameObject(float x, float y, ID id){
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick();
public abstract void render(Graphics g);
public abstract Rectangle getBounds();
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public int getX(){
return (int) x;
}
public int getY(){
return (int) y;
}
public void setId(ID id){
this.id = id;
}
public ID getId(){
return id;
}
public void setVelX(int velX){
this.velX = velX;
}
public void setVelY(int velY){
this.velY = velY;
}
public float getVelX(){
return velX;
}
public float getVelY(){
return velY;
}
}
The excetion is caused by this constructor call:
new Color(75, (float) greenValue, 0)
You use the Color(float, float, float), since the second parameter has type float. As documented in the javadocs, this constructor takes 3 floats that represent rgb components. Ranges are from 0.0f to 1.0f, not from 0 to 255, which is why you get the error (75 is too large).
It seems like you should not cast the second parameter to make that statement use the Color(int, int, int) constructor.

Categories

Resources