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.....
Related
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();
}
}
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
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.
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.
So I've pretty much thrown together a basic game in java by following a bunch of different tutorials - the problem is i cant manage to figure out how to get my sprite to move in different directions. Here is the code for my main
package com.game.src.main;
import java.awt.Canvas;
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.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 850;
public static final int HEIGHT = 650;
public static final int SCALE = 1;
public final String TITLE = "Racing Game!";
static ServerSocket serverSocket;
static Socket socket;
static DataOutputStream out;
private boolean running = false;
private Thread thread;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
private BufferedImage spriteSheet = null;
private BufferedImage spriteSheet2 = null;
private BufferedImage background = null;
private BufferedImage MenuBackground = null;
private Player p;
private Player2 p2;
private Menu menu;
public static enum STATE {
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/Sprite_Sheet.png");
background = loader.loadImage("/Track.png");
MenuBackground = loader.loadImage("/MenuBG.fw.png");
}
catch (IOException e) {
e.printStackTrace();
}
menu = new Menu();
addKeyListener(new KeyInput(this));
this.addMouseListener(new MouseInput());
p = new Player(365, 500, this);
p2 = new Player2(365, 550, this);
}
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 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--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " FPS, TICKS " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
private void tick() {
if(State == STATE.GAME){
p.tick();
p2.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.drawImage(MenuBackground, 0, 0, null);
if(State == STATE.GAME){
//Drawing the main games background
g.drawImage(background, 0, 0, null);
p.render(g);
p2.render(g);
}
else if(State == STATE.MENU){
menu.render(g);
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(State == STATE.GAME){
if(key == KeyEvent.VK_RIGHT){
p.setVelX(5);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(5);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(-5);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(-5);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(5);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(5);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(-5);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(-5);
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT){
p.setVelX(0);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(0);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(0);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(0);
}
}
public static void main(String args[]) throws Exception {
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
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();
System.out.println("Starting server....");
serverSocket = new ServerSocket(7777);
System.out.println("Server started");
socket = serverSocket.accept();
System.out.println("Connecting from: " + socket.getInetAddress());
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("This is a test of Java Sockets");
System.out.println("Data has been sent");
}
public BufferedImage getSpriteSheet() {
return spriteSheet;
}
public BufferedImage getSpriteSheet2() {
return spriteSheet2;
}
}
This is my player class
package com.game.src.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class Player {
private double x;
private double y;
private double velX = 0;
private double velY = 0;
private BufferedImage player;
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage SpriteSheet = null;
public Player(double x, double y, Game game) {
this.x = x;
this.y = y;
//New instance of Sprite sheet - reading from buffered image loader
SpriteSheet ss = new SpriteSheet(game.getSpriteSheet());
player = ss.grabImage(1, 1, 50, 50);
try {
SpriteSheet = loader.loadImage("/Sprite_Sheet.png");
}
catch(Exception e) {
e.printStackTrace();
}
}
public void tick() {
x+=velX;
y+=velY;
//Adding basic collision
if(x < 0 + 50) {
x = 0 + 50;
}
if(x >= 850 - 100) {
x = 850 - 100;
}
if(y < 0 + 100) {
y = 0 + 100;
}
if(y >= 650 - 100){
y = 650 - 100;
}
}
public void render(Graphics g){
//Draw Track
Color c1 = Color.green;
g.setColor( c1 );
g.fillRect( 150, 200, 550, 300 ); //grass
Color c2 = Color.black;
g.setColor( c2 );
g.drawRect(50, 100, 750, 500); // outer edge
g.drawRect(150, 200, 550, 300); // inner edge
Color c3 = Color.yellow;
g.setColor( c3 );
g.drawRect( 100, 150, 650, 400 ); // mid-lane marker
Color c4 = Color.white;
g.setColor( c4 );
g.drawLine( 425, 500, 425, 600 ); // start line
g.drawImage(player, (int)x, (int)y, null);
}
public double getX(Graphics g){
return x;
}
public double getY(){
return y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public void setVelX(double velX){
this.velX = velX;
}
public void setVelY(double velY){
this.velY = velY;
}
}
I have two players in this game but i'm really stuck on how i can change the sprites direction by 22.5% in a desired direction so if i pressed the up key for player 1 it would rotate my car 22.5% north etc. I have a sprite sheet with 16 sprites for each player for every change in angle by 22.5% This is really confusing me and i'm not sure how i can implement this,
Thanks for taking the time to look
This is a basic example of spinning a sprite
What this is maintain's a virtual state which the Player object inspects in order to determine how it should be changed accordingly. This separates the action from the result, meaning that it would be possible to substitute the action (arrow up key) with some other action, but still obtain the same result.
This example also uses the key bindings API, which doesn't suffer from the same focus related issues that KeyListener does, but this is a pure Swing API and won't be compatiable with Canvas, but is a nice demonstration ;)
The real magic occurs in the characters paint method...
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
Basically, this creates a AffineTransformation which is then compounded to produce the result we need. That is, first it's anchor position is translated to the characters x/y position and then rotated about the characters center point. Because it's been translated, we can simply paint the character at 0x0. This much easier then try to calculate the characters rotation anchor somewhere else in virtual space - IMHO
The character is rotated by pressing either the Up or Down arrow keys. While pressed, the character will continue to rotate, this is a feature of the example for demonstration purpose.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RotateCharater {
public static void main(String[] args) {
new RotateCharater();
}
public RotateCharater() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultState state;
private Player player;
public TestPane() {
player = new Player();
state = new DefaultState();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "upKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "upKeyReleased");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "downKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "downKeyReleased");
ActionMap am = getActionMap();
am.put("upKeyPressed", new UpKeyAction(state, true));
am.put("upKeyReleased", new UpKeyAction(state, false));
am.put("downKeyPressed", new DownKeyAction(state, true));
am.put("downKeyReleased", new DownKeyAction(state, false));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
player.update(state);
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
player.paint(g2d);
g2d.dispose();
}
public class UpKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public UpKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setUpKeyPressed(pressed);
}
}
public class DownKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public DownKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setDownKeyPressed(pressed);
}
}
}
public interface State {
public boolean isUpKeyPressed();
public boolean isDownKeyPressed();
}
public class DefaultState implements State {
private boolean upKeyPressed;
private boolean downKeyPressed;
public boolean isDownKeyPressed() {
return downKeyPressed;
}
public boolean isUpKeyPressed() {
return upKeyPressed;
}
public void setDownKeyPressed(boolean downKeyPressed) {
this.downKeyPressed = downKeyPressed;
upKeyPressed = false;
}
public void setUpKeyPressed(boolean upKeyPressed) {
this.upKeyPressed = upKeyPressed;
downKeyPressed = false;
}
}
public class Player {
private BufferedImage character;
private int x = 100 - 32, y = 100 - 32;
private double angle;
public Player() {
try {
character = ImageIO.read(getClass().getResource("/Character.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
public void update(State state) {
if (state.isUpKeyPressed()) {
angle -= 22.5;
} else if (state.isDownKeyPressed()) {
angle += 22.5;
}
}
}
}
Remember, this is just an example used to present the concept ;)