Java - MouseListener Does Not Work - java

I have been trying to create a functional button for a basic Java game, but whenever I click on the screen (literally anywhere within or out of the parameters I have), there is no function in my game. I am trying to figure out where I have my conflict that the mouse event is not working. I have double and triple checked almost everything and I cannot find the issue. I included the Game Class and Menu class but if the other Classes are needed I will post them. I also know that the code is most likely very sloppy and improper, but I am just learning and trying to teach myself some of the basics.
Is the problem with the "STATE" enum I created?
Can the issue be somewhere within the boolean mouseOver?
I am super confused and don't understand where exactly I am messing up on this. I want to be able to have the functionality I need for the game. Sorry if this is a really basic question or the code is horrible, I'll take any help you can offer.
package com.test.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 = 5348695609807625849L;
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 Spawn spawner;
private Menu menu;
public enum STATE {
Menu,
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, "GafGin", this);
hud = new HUD();
spawner = new Spawn(handler, hud);
r = new Random();
if(gameState == STATE.Game) {
handler.addObject(new Player(WIDTH/2-32, HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, 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() {
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--;
gameOver();
}
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();
}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(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
if(gameState == STATE.Game) {
hud.render(g);
}else if(gameState == STATE.Menu) {
menu.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 void gameOver() {
if(HUD.HEALTH <= 0) {
handler.endGame();
}
checkRunning();
}
public void checkRunning() {
if(Handler.getGameEnded() == true) {
running = false;
}
}
public static void main(String[] args) {
new Game();
}
}
package com.test.main;
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 com.test.main.Game.STATE;
public class Menu extends MouseAdapter{
private Game game;
private Handler handler;
private Random r = new Random();
public Menu(Game game, Handler handler) {
this.game = game;
this.handler = handler;
}
public void MousePressed(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(mouseOver(mx, my, (Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) - 64, 250, 64)){
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH/2-32, Game.HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, handler));
}
if(mouseOver(mx, my, 100, 100, 250, 64)) {
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH/2-32, Game.HEIGHT/2-32, ID.Player, handler));
handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH - 50), r.nextInt(Game.HEIGHT - 50), ID.BasicEnemy, 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, 50);
Font fnt2 = new Font("arial", 1, 30);
g.setColor(Color.white);
g.drawRect(100, 100, 250, 64);
g.setFont(fnt);
g.setColor(Color.white);
g.drawString("Menu", (Game.WIDTH / 2) - 85, (Game.HEIGHT / 2) - 124);
g.setFont(fnt2);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) - 64, 250, 64);
g.drawString("Play", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) - 22);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2), 250, 64);
g.drawString("Quit", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) + 42);
g.setColor(Color.white);
g.drawRect((Game.WIDTH / 2) - 140, (Game.HEIGHT / 2) + 64, 250, 64);
g.drawString("Help", (Game.WIDTH / 2) - 52, (Game.HEIGHT / 2) + 106);
}
}

Related

The button to Quit the game on my menu is not closing the game

I am trying to make a menu for a game and can't get the "quit" button to work. This is for a school project and I'm not the greatest at coding, I recently started using eclipse and still unfamiliar with many things in java. any help would be much appreciated.
Iv'e tried searching for a solution to the problem but cant find one.
package com.game.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 = -473349850293143017L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Menu menu;
public enum STATE {
Menu,
Game
};
public STATE gameState = STATE.Menu;
public Game() {
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Learning About Animals", this);
//create handlerby replacing null: the actual game
menu = new Menu(this);
if(gameState == STATE.Game);
}
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 render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//changes colour
g.setColor(Color.green);
g.fillRect(0, 0, WIDTH, HEIGHT);
if(gameState == STATE.Game)
{
hud.render(g);
}else if(gameState == STATE.Menu) {
menu.render(g);
}
g.dispose();
bs.show();
}
private void tick(){
if(gameState == STATE.Game)
{
hud.tick();
}else if(gameState == STATE.Menu) {
menu.tick();
}
}
public static void main(String args[]) {
new Game();
}
}
package com.game.main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.game.main.Game.STATE;
public class Menu extends MouseAdapter{
private Game game;
public Menu(Game game) {
this.game = game;
}
public void mousePressed(MouseEvent e){
int mx = e.getX();
int my = e.getY();
//play button
if (mouseOver(mx, my, 210, 150 ,200, 64)) {
game.gameState = STATE.Game;
}
//Quit button
if (mouseOver(mx, my, 210, 350 ,200, 64)) {
System.exit(1);
}
}
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, 50);
Font fnt2 = new Font("arial", 1, 30);
g.setFont(fnt);
g.setColor(Color.white);
g.drawString("MENU", 240, 70);
g.setFont(fnt2);
g.drawRect(210, 150, 200, 64);
g.drawString("PLAY", 270, 190);
g.setFont(fnt2);
g.drawRect(210, 250, 200, 64);
g.drawString("HELP", 270, 290);
g.setFont(fnt2);
g.drawRect(210, 350, 200, 64);
g.drawString("QUIT", 270, 390);
}
}
Looking for help to get my exit button working Im getting something saying source not found for MouseAdapter class.

Printing a timer that updates every second into a simple game

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class FinalFlappy implements ActionListener, MouseListener,
KeyListener
{
public static FinalFlappy finalFlappy;
public final int WIDTH = 800, HEIGHT = 800;
public FinalFlappyRend renderer;
public Rectangle bee;
public ArrayList<Rectangle> rect_column;
public int push, yMotion, score;
public boolean gameOver, started;
public Random rand;
public FinalFlappy()
{
JFrame jframe = new JFrame();
Timer timer = new Timer(16, this);
renderer = new FinalFlappyRend();
rand = new Random();
jframe.add(renderer);
jframe.setTitle("Flappy Bee");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(WIDTH, HEIGHT);
jframe.addMouseListener(this);
jframe.addKeyListener(this);
jframe.setResizable(false);
jframe.setVisible(true);
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column = new ArrayList<Rectangle>();
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
timer.start();
}
public void addColumn(boolean start)
{
int space = 300;
int width = 60;
int height = 50 + rand.nextInt(300);
if (start)
{
rect_column.add(new Rectangle(WIDTH + width + rect_column.size() * 300, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(WIDTH + width + (rect_column.size() - 1) * 300, 0, width, HEIGHT - height - space));
}
else
{
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x + 600, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x, 0, width, HEIGHT - height - space));
}
}
public void jump()
{
if (gameOver)
{
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column.clear();
yMotion = 0;
score = 0;
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
gameOver = false;
}
if (!started)
{
started = true;
}
else if (!gameOver)
{
if (yMotion > 0)
{
yMotion = 0;
}
yMotion -= 10;
}
}
#Override
public void actionPerformed(ActionEvent e)
{
int speed = 10;
push++;
if (started)
{
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
column.x -= speed;
}
if (push % 2 == 0 && yMotion < 15)
{
yMotion += 2;
}
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
if (column.x + column.width < 0)
{
rect_column.remove(column);
if (column.y == 0)
{
addColumn(false);
}
}
}
bee.y += yMotion;
for (Rectangle column : rect_column)
{
if (column.y == 0 && bee.x + bee.width / 2 > column.x + column.width / 2 - 10 && bee.x + bee.width / 2 < column.x + column.width / 2 + 10)
{
score++;
}
if (column.intersects(bee))
{
gameOver = true;
if (bee.x <= column.x)
{
bee.x = column.x - bee.width;
}
else
{
if (column.y != 0)
{
bee.y = column.y - bee.height;
}
else if (bee.y < column.height)
{
bee.y = column.height;
}
}
}
}
if (bee.y > HEIGHT - 120 || bee.y < 0)
{
gameOver = true;
}
if (bee.y + yMotion >= HEIGHT - 120)
{
bee.y = HEIGHT - 120 - bee.height;
gameOver = true;
}
}
renderer.repaint();
}
public void paintColumn(Graphics g, Rectangle column)
{
g.setColor(Color.green.darker());
g.fillRect(column.x, column.y, column.width, column.height);
g.fillRect(column.x-20, column.y+column.height-10, column.width+40, 10);
g.fillRect(column.x-20, column.y-10, column.width+40, 10);
}
public void repaint(Graphics g)
{
g.setColor(new Color(153,204,255));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(255,255,255));
g.fillOval(50, 50, 100, 100);
g.setColor(Color.YELLOW);
g.fillOval(600, 50, 100, 100);
g.setColor(new Color(156,93,82));
g.fillRect(0, HEIGHT - 120, WIDTH, 120);
g.setColor(new Color(128,255,0));
g.fillRect(0, HEIGHT - 120, WIDTH, 20);
g.setColor(Color.YELLOW);
g.fillRect(bee.x, bee.y, bee.width, bee.height);
for (Rectangle column : rect_column)
{
paintColumn(g, column);
}
g.setColor(Color.white);
g.setFont(new Font("Times New Roman", 1, 100));
if (!started)
{
g.drawString("Push A to start", 100, HEIGHT / 2 - 50);
}
if (gameOver)
{
g.drawString("Game Over", 100, HEIGHT / 2 - 50);
g.drawString("A to replay", 100, HEIGHT / 2 + 90);
}
}
public static void main(String[] args)
{
finalFlappy = new FinalFlappy();
}
#Override
public void mouseClicked(MouseEvent e)
{
jump();
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_A)
{
jump();
}
}
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class FinalFlappyRend extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
FinalFlappy.finalFlappy.repaint(g);
}
}
I am working on making a Flappy bird game and I am stuck on how to make and display a timer that updates every second onto the screen
How do I make it start as the game starts and end as the game over pops up?
There are a few ways you might achieve what you're asking. The important thing to remember is, any solution is going to have a degree of drift, meaning that it's unlikely to absolutely accurate, the degree of drift will depend on a lot of factors, so just beware.
You could use a Swing Timer
It's among the safest means for updating the UI on a regular basis, it's also useful if your main loop is already based on a Swing Timer
See How to Use Swing Timers for more details
You could...
Maintain some kind of counter within in your main loop. This assumes that you're using a separate thread (although you can do the same thing with a Swing Timer) and are simply looping at some consistent rate
long tick = System.nanoTime();
long lastUpdate = -1;
while (true) {
long diff = System.nanoTime() - tick;
long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.NANOSECONDS);
if (seconds != lastUpdate) {
lastUpdate = seconds;
updateTimerLabel(seconds);
}
Thread.sleep(100);
}
This basically runs a while-loop, which calculates the difference between a given point in time (tick) and now, if it's a "second" difference, it then updates the UI (rather than constantly updating the UI with the same value)
The updateTimerLabel method basically updates the label with the specified time, but does so in a manner which is thread safe
protected void updateTimerLabel(long seconds) {
if (EventQueue.isDispatchThread()) {
timerLabel.setText(Long.toString(seconds));
} else {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
updateTimerLabel(seconds);
}
});
}
}
To make and display a timer that updates every second, Put this code in your main class:
private Timer timer = new Timer();
private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);
timer.schedule(new UpdateUITask(), 0, 1000);
private class UpdateUITask extends TimerTask {
int nSeconds = 0;
#Override
public void run() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
timeLabel.setText(String.valueOf(nSeconds++));
}
});
}
}

Screen Size auto adjust

so currently I am in the process of making a game, and I want to make it easy so that all screen sizes can use it. But I don't know how to do this, currently I just have it set so the default resolution is 1600 x 900. If you guys know how I can make this adjustable for all sizes I would appreciate the help :)
I have look through all my code but I don't know what I have to do to make this work, if you need more information on my problem just ask.
Many thanks,
Ash
package net.captainash123.minitale;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Main extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
public static byte pixelSize = 5;
public static int moveFromBorder = 0;
public static double sX = moveFromBorder, sY = moveFromBorder;
public static double dir = 0;
public static int width = 1600;
public static int height = 900;
public int timer = 0;
public byte movingTimer = 0;
public static Dimension realSize;
public static Dimension size = new Dimension(1600, 900);
public static Dimension pixel = new Dimension(size.width / pixelSize, size.height / pixelSize);
public static Point mse = new Point(0, 0);
public static String name = "Minitale: Beta - 1.1.3";
public static String deathText = "You Died";
public static boolean isRunning = false;
public static boolean isMoving = false;
public static boolean isJumping = false;
public static boolean isMouseLeft = false;
public static boolean isMouseRight = false;
private Image screen;
public int FPS;
public int totalTime;
public static Level level;
public static Character character;
public static Inventory inventory;
public static CraftingTable craftingTable;
public static Sky sky;
public static Checker checker;
public static ArrayList<Mob> mob = new ArrayList<Mob>();
public Main() {
setPreferredSize(size);
addKeyListener(new Listening());
addMouseListener(new Listening());
addMouseMotionListener(new Listening());
addMouseWheelListener(new Listening());
}
public void start() {
requestFocus();
//Defining objects etc.
new Tile(); //Loading Images.
level = new Level();
character = new Character(Tile.tileSize, Tile.tileSize * 2);
inventory = new Inventory();
craftingTable = new CraftingTable();
Furnace furnace = new Furnace();
sky = new Sky();
checker = new Checker();
//mob.add(new Zombie(50, 10, Tile.tileSize, Tile.tileSize * 2, Tile.zombie));
//mob.add(new P2(60, 10, Tile.tileSize, Tile.tileSize * 2, Tile.P2));
//mob.add(new Turtle(40, 10, Tile.tileSize * 2, Tile.tileSize, Tile.turtle));
mob.add(new Chicken(40, 10, Tile.tileSize, Tile.tileSize, Tile.chicken));
mob.add(new Pig(60, 10, Tile.tileSize, Tile.tileSize, Tile.pig));
//Starting game loop.
isRunning = true;
new Thread(this).start();
}
public void stop() {
isRunning = false;
}
private static JFrame frame;
public static void main(String args[]) {
Main component = new Main();
frame = new JFrame();
frame.add(component);
frame.setIconImage(new ImageIcon("assets/textures/gui/gameIcon.png").getImage());
frame.pack();
realSize = new Dimension(frame.getWidth(), frame.getHeight());
frame.setTitle(name);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
component.start();
}
public void tick() {
if(frame.getWidth() != realSize.width || frame.getHeight() != realSize.height) {
frame.pack();
}
character.tick();
level.tick((int) sX, (int) sY, (pixel.width / Tile.tileSize) + 2, (pixel.height / Tile.tileSize) + 2);
sky.tick();
checker.tick();
craftingTable.checkRecipes();
Furnace.checkRecipes();
for(int i = 0; i < mob.toArray().length; i++) {
mob.get(i).tick();
}
}
public void render() {
Graphics g = screen.getGraphics();
//Drawing things. //102, 178, 255 blue sky.
sky.render(g);
level.render(g, (int) sX, (int) sY, (pixel.width / Tile.tileSize) + 2, (pixel.height / Tile.tileSize) + 2);
character.render(g);
for(int i = 0; i < mob.toArray().length; i++) {
mob.get(i).render(g);
}
inventory.render(g);
craftingTable.render(g);
Furnace.render(g);
if(character.isDead) {
g.setColor(Color.BLACK); //255, 0 ,0, 50
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
g.setFont(new Font("Calibri", Font.BOLD, 24));
g.drawString(deathText, 116, 150);
}
if(timer < 270) {
timer++;
movingTimer++;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
if(movingTimer > 10) {
}
if(movingTimer > 20){
movingTimer = 0;
}
g.setColor(new Color(108, 108, 108));
g.setFont(new Font("Calibri", Font.BOLD, 24));
g.drawString("Minitale", width / 16 + 16, height / 8 + 30);
g.drawImage(Tile.Splash, width / 32 + 34, height / 32 - 40, null);
}
g = getGraphics();
g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null);
g.dispose();
}
public void run() {
screen = createVolatileImage(pixel.width, pixel.height);
int frames = 0;
double nonProcessedSeconds = 0;
long previousTime = System.nanoTime();
double secondsPerTick = 1 / 60.0;
int tickCount = 0;
boolean hasTicked = false;
int totalTime = 0;
while(isRunning) {
long currentTime = System.nanoTime();
long passedTime = currentTime - previousTime;
previousTime = currentTime;
nonProcessedSeconds += passedTime / 1000000000.0;
while(nonProcessedSeconds > secondsPerTick) {
tick();
nonProcessedSeconds -= secondsPerTick;
hasTicked = true;
tickCount++;
if(tickCount % 60 == 0) {
previousTime += 1000;
FPS = frames;
frames = 0;
}
}
if(hasTicked) {
frames++;
}
frames++;
requestFocus();
tick();
render();
try {
Thread.sleep(5);
} catch(Exception e){ }
}
}
}
You can get the screen size with the Toolkit.getScreenSize() method.
See How can I get screen resolution in java?

Make circles randomly dis/appear & change color using Swing Timer

So I'm making a game where you jump on rocks and you must not jump on rock which is covered by water. I'm stuck at the part where rocks (circles) randomly disappear in water and randomly appear and around 1.5 seconds before they disappear make it change color. I think its best to use javax.swing.Timer.
Could you help me achieve that?
Here is my code so far:
Main class:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferStrategy;
import java.util.Random;
import javax.swing.Timer;
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) {
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) {
Random r = new Random();
long now = System.currentTimeMillis();
int b = 0;
//System.out.println(now);
long extraSeconds = 500;
}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();
long now = System.currentTimeMillis();
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);
}
if(gameState == STATE.Game) {
}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();
}
}
GameObject 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;
}
}
Handler class:
package com.pitcher654.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);
}
}
ID class:
package com.pitcher654.main;
public enum ID {
Player(),
Player2(),
BasicEnemy(),
Misc();
}
KeyInput class:
package com.pitcher654.main;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyInput extends KeyAdapter{
private Handler handler;
public KeyInput(Handler handler) {
this.handler = handler;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
for(int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player) {
//kez events for Player 1
//GameObject object = new GameObject(0, 0, ID.Misc);
//System.out.println(tempObject.getID());
if(GameObject.x != 500) {
if(key == KeyEvent.VK_RIGHT) {
Player.currentStone++;
tempObject.setX(tempObject.getX() + 100);
}
}
if(GameObject.x != 100){
if(key == KeyEvent.VK_LEFT) {
Player.currentStone--;
tempObject.setX(tempObject.getX() - 100);
}
}
}
}
if(key == KeyEvent.VK_ESCAPE) System.exit(1);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
}
}
Menu class:
package com.pitcher654.main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.pitcher654.main.Game.STATE;
public class Menu extends MouseAdapter{
private Game game;
private Handler handler;
private GameObject Player;
public Menu(Game game, Handler handler) {
this.game = game;
this.handler = handler;
}
public void mouseClicked(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(game.gameState == STATE.Menu) {
//play 1 button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 150, 250, 64)) {
game.gameState = STATE.Game;
handler.addObject(new Player(100, 200, ID.Player));
//handler.addObject(new BasicEnemy(0, 0, ID.BasicEnemy));
}
//Instructions button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 250, 250, 64)) {
game.gameState = STATE.Help;
}
//Quit button
if(mouseOver(mx, my, (Game.WIDTH - 250) / 2, 350, 250, 64)) {
System.exit(1);
}
}
//Bacl to menu in game button
if(game.gameState == STATE.Help) {
if(mouseOver(mx, my, 23, 395, 100, 32)) {
game.gameState = STATE.Menu;
//handler.object.remove(Player);
}
}
}
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) {
if(game.gameState == STATE.Menu) {
Font fnt = new Font("Trebuchet MS", 30, 15);
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, game.WIDTH, game.HEIGHT);
g.setColor(Color.white);
g.setFont(new Font("Papyrus", 1, 50));
g.drawString("Price iz davnine", (Game.WIDTH - 250) / 2 - 50, 70);
g.drawRect((Game.WIDTH - 250) / 2, 150, 250, 64);
g.drawRect((Game.WIDTH - 250) / 2, 250, 250, 64);
g.drawRect((Game.WIDTH - 250) / 2, 350, 250, 64);
g.setFont(new Font("Trebuchet MS", 5000, 20));
g.drawString("Play", (Game.WIDTH - 250) / 2 + 110, 190);
g.setFont(fnt);
g.drawString("How to Play", (Game.WIDTH - 250) / 2 + 85, 290);
g.drawString("Quit", (Game.WIDTH - 250) / 2 + 105, 390);
}else if(game.gameState == STATE.Help) {
g.setColor(Color.white);
g.setFont(new Font("Papyrus", 1, 50));
g.drawString("How to play", (Game.WIDTH - 250) / 2 - 50, 70);
g.setFont(new Font("Trebuchetr MS", 30, 10));
g.drawRect(23, 395, 100, 32);
g.setColor(Color.black);
g.drawString("Back to Menu", 33, 415);
}
}
}
Player class:
package com.pitcher654.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Timer;
import com.pitcher654.main.Game.STATE;
public class Player extends GameObject {
Random r = new Random();
public static int currentStone = 1;
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);
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 window class:
package com.pitcher654.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends Canvas{
private static final long serialVersionUID = 9086330915853125521L;
BufferedImage image = null;
URL url = null;
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
try {
image = ImageIO.read(new URL("https://static.wixstatic.com/media/95c249_b887de2536aa48cb962e2336919d2693.png/v1/fill/w_600,h_480,al_c,usm_0.66_1.00_0.01/95c249_b887de2536aa48cb962e2336919d2693.png"));
} catch (IOException e) {
e.printStackTrace();
}
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setIconImage(image);
//DrawingPanel panel = new DrawingPanel();
//frame.getContentPane().add(panel);
frame.setVisible(true);
frame.requestFocus();
game.start();
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -7662876024842980779L;
public void paintComponent(Graphics g) {
g.setColor(new Color(209, 155, 29));
g.fillOval(100, 100, 100, 100);
}
}
}
Based on you code, a Swing Timer isn't what you want. You already have a "game/main" loop which should be updating the current state of the game on each cycle and rendering it, you simply need to devise a means by which you can create a "rock", with a given life span, each time it's rendered, it needs to check if it's life span is nearly over and have it removed when it dies.
The rock is really just another entity in your game, which can be updated and rendered.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RockyRoad {
public static void main(String[] args) {
new RockyRoad();
}
public RockyRoad() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static 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 rnd;
private List<Entity> entities = new ArrayList<>(25);
public enum STATE {
Menu,
Help,
Game
};
public STATE gameState = STATE.Game;
public Game() {
rnd = new Random();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
start();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
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) {
update();
render();
}
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
//System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick() {
//hud.tick();
}
protected void update() {
if (gameState == STATE.Game) {
if (rnd.nextBoolean()) {
System.out.println("New...");
int x = rnd.nextInt(getWidth() - Rock.SIZE);
int y = rnd.nextInt(getHeight() - Rock.SIZE);
int lifeSpan = 4000 + rnd.nextInt(6000);
entities.add(new Rock(lifeSpan, x, y));
}
List<Entity> toRemove = new ArrayList<>(entities.size());
List<Entity> control = Collections.unmodifiableList(entities);
for (Entity entity : entities) {
if (entity.update(control, this) == EntityAction.REMOVE) {
System.out.println("Die...");
toRemove.add(entity);
}
}
entities.removeAll(toRemove);
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
long now = System.currentTimeMillis();
g.setColor(new Color(87, 124, 212));
g.fillRect(0, 0, WIDTH, HEIGHT);
if (gameState == STATE.Game) {
g.setColor(new Color(209, 155, 29));
if (gameState == STATE.Game) {
for (Entity entity : entities) {
entity.render(g, this);
}
}
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 interface Renderable {
public void render(Graphics2D g2d, Component parent);
}
public enum EntityAction {
NONE,
REMOVE;
}
public interface Entity extends Renderable {
// In theory, you'd pass the game model which would determine
// all the information the entity really needed
public EntityAction update(List<Entity> entities, Component parent);
}
public static class Rock implements Renderable, Entity {
protected static final int SIZE = 20;
private int lifeSpan;
private long birthTime;
private int x, y;
public Rock(int lifeSpan, int x, int y) {
if (lifeSpan <= 1500) {
throw new IllegalArgumentException("Life span for a rock can not be less then or equal to 1.5 seconds");
}
this.lifeSpan = lifeSpan;
birthTime = System.currentTimeMillis();
this.x = x;
this.y = y;
}
#Override
public void render(Graphics2D g2d, Component parent) {
long age = System.currentTimeMillis() - birthTime;
if (age < lifeSpan) {
if (age < lifeSpan - 1500) {
g2d.setColor(Color.BLUE);
} else {
g2d.setColor(Color.RED);
}
g2d.fillOval(x, y, SIZE, SIZE);
}
}
#Override
public EntityAction update(List<Entity> entities, Component parent) {
EntityAction action = EntityAction.NONE;
long age = System.currentTimeMillis() - birthTime;
System.out.println("Age = " + age + "; lifeSpan = " + lifeSpan);
if (age >= lifeSpan) {
action = EntityAction.REMOVE;
}
return action;
}
}
}

Java: Place an Image over a shape

I have been working on a simple Java game and have done so successfully using shapes, but the next big step is to do so using images. I was wondering whether there was a method where I could simply place an image over a shape such as a rectangle, which would make the process much easier and doesn't require me to re-write most of my code.
Here's the two classes of my game for reference:
The first class named "Flappy Bird"
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class FlappyBird implements ActionListener, MouseListener, KeyListener {
public static FlappyBird flappyBird;
public final int WIDTH = 800, HEIGHT = 800;
public Renderer renderer;
public Rectangle bird;
public ArrayList<Rectangle> columns;
public int ticks, yMotion, score;
public boolean gameOver, started;
public Random rand;
public FlappyBird() {
JFrame jframe = new JFrame();
Timer timer = new Timer(20, this);
renderer = new Renderer();
rand = new Random();
jframe.add(renderer);
jframe.setTitle("Flappy Bird");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(WIDTH, HEIGHT);
jframe.addMouseListener(this);
jframe.addKeyListener(this);
jframe.setResizable(false);
jframe.setVisible(true);
bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);
columns = new ArrayList<Rectangle>();
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
timer.start();
}
public void addColumn(boolean start) {
int space = 300;
int width = 100;
int height = 50 + rand.nextInt(300);
if (start) {
columns.add(new Rectangle(WIDTH + width + columns.size() * 300, HEIGHT - height - 120, width, height));
columns.add(new Rectangle(WIDTH + width + (columns.size() - 1) * 300, 0, width, HEIGHT - height - space));
} else {
columns.add(new Rectangle(columns.get(columns.size() - 1).x + 600, HEIGHT - height - 120, width, height));
columns.add(new Rectangle(columns.get(columns.size() - 1).x, 0, width, HEIGHT - height - space));
}
}
public void paintColumn(Graphics g, Rectangle column) {
g.setColor(Color.green.darker());
g.fillRect(column.x, column.y, column.width, column.height);
}
public void jump() {
if (gameOver) {
bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);
columns.clear();
yMotion = 0;
score = 0;
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
gameOver = false;
}
if (!started)
started = true;
else if (!gameOver) {
if (yMotion > 0)
yMotion = 0;
yMotion -= 10;
}
}
#Override
public void actionPerformed(ActionEvent e) {
int speed = 10;
ticks++;
if (started) {
for (int i = 0; i < columns.size(); i++) {
Rectangle column = columns.get(i);
column.x -= speed;
}
if (ticks % 2 == 0 && yMotion < 15)
yMotion += 2;
for (int i = 0; i < columns.size(); i++) {
Rectangle column = columns.get(i);
if (column.x + column.width < 0) {
columns.remove(column);
if (column.y == 0)
addColumn(false);
}
}
bird.y += yMotion;
for (Rectangle column : columns) {
if (column.y == 0 && bird.x + bird.width / 2 > column.x + column.width / 2 - 10 && bird.x + bird.width / 2 < column.x + column.width / 2 + 10) {
score++;
}
if (column.intersects(bird)) {
gameOver = true;
if (bird.x <= column.x)
bird.x = column.x - bird.width;
else
if (column.y != 0)
bird.y = column.y - bird.height;
else if (bird.y < column.height)
bird.y = column.height;
}
}
if (bird.y > HEIGHT - 120 || bird.y < 0)
gameOver = true;
if (bird.y + yMotion >= HEIGHT - 120) {
bird.y = HEIGHT - 120 - bird.height;
gameOver = true;
}
}
renderer.repaint();
}
public void repaint(Graphics g) {
g.setColor(Color.cyan);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.orange);
g.fillRect(0, HEIGHT - 120, WIDTH, 120);
g.setColor(Color.green);
g.fillRect(0, HEIGHT - 120, WIDTH, 20);
g.setColor(Color.red);
g.fillRect(bird.x, bird.y, bird.width, bird.height);
for (Rectangle column : columns)
paintColumn(g, column);
g.setColor(Color.white);
g.setFont(new Font("Arial", 1, 100));
if (!started)
g.drawString("Click to start!", 75, HEIGHT / 2 - 50);
if (gameOver)
g.drawString("Game Over!", 100, HEIGHT / 2 - 50);
if (!gameOver && started)
g.drawString(String.valueOf(score), WIDTH / 2 - 25, 100);
}
public static void main(String[] args) {
flappyBird = new FlappyBird();
}
#Override
public void mouseClicked(MouseEvent e) {
jump();
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
jump();
}
#Override
public void mousePressed(MouseEvent e){
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e){
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
}
The second class named "Renderer":
import java.awt.Graphics;
import javax.swing.JPanel;
public class Renderer extends JPanel {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FlappyBird.flappyBird.repaint(g);
}
}
I know this is a massive ask and I would like to give a HUGE thank you to everyone who replies and to the wonderful community here :-)

Categories