I created a class that draws a ball on a screen and my goal is to move it with the keys, but the ball stays in one spot. the coordinates of the ball change according to the key presses but not the actual ball itself
import java.applet.Applet;
import java.awt.Color;
import java.awt.Component;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class game extends Applet implements Runnable
{
static final int WIDTH = 450;
static final int HEIGHT = 450;
private Image dbImage;
private Graphics dbg;
public static long NEW_DOT_FREQ = TimeUnit.SECONDS.toMillis(3);
public long lastUpdateTime;
public long timeSinceLastNewDot;
public ArrayList<Ball> BALLS;
Color[] color = {Color.red, Color.blue, Color.green, Color.yellow, Color.magenta, Color.black};
int colorIndex;
static final int NUM_OF_BALLS = 4;
int i;
int t;
MainBall mainBall = new MainBall(100, 100, 10, 10, 100, 100, 0, 0);
Thread updateTime = new updateTime();
public void start()
{
lastUpdateTime = System.currentTimeMillis();
Thread th = new Thread(this);
th.start();//start main game
updateTime.start();
}
public void updateGame()
{
//Get the current time
long currentTime = System.currentTimeMillis();
//Calculate how much time has passed since the last update
long elapsedTime = currentTime - lastUpdateTime;
//Store this as the most recent update time
lastUpdateTime = currentTime;
//Create a new dot if enough time has passed
//Update the time since last new dot was drawn
timeSinceLastNewDot += elapsedTime;
if (timeSinceLastNewDot >= NEW_DOT_FREQ)
{
int newX = randomNumber();
int newY = randomNumber();
debugPrint("New dot created at x:" + newX + ", y:" + newY + ".");
BALLS.add(new Ball(newX, newY, 20, 20));
timeSinceLastNewDot = 0;
}
}
private void debugPrint(String value)
{
System.out.println(value);
}
public class updateTime extends Thread implements Runnable
{
public void run()
{
for(t = 0; ; t++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
public int randomNumber()
{
return (int)(Math.random() * 400);
}
public int getRandomColor()
{
return (int)(Math.random() * 6);
}
public class MainBall
{
int x;
int y;
int width;
int height;
int xpos = 100;
int ypos = 100;
int xspeed = 0;
int yspeed = 0;
public MainBall(int x, int y, int width, int height, int xpos, int ypos, int xspeed, int yspeed)
{
this.x = 100;
this.y = 100;
this.width = 10;
this.height = 10;
this.xpos = 100;
this.ypos = 100;
this.xspeed = 0;
this.yspeed = 0;
}
public void paintMainBall(Graphics g)
{
g.setColor(Color.black);
g.fillOval(x, y, width, height);
g.drawString(xpos + ", " + ypos, 20, 40);
}
}//mainBall
class Ball
{
int x;
int y;
int width;
int height;
public Ball(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}//end ball
public void paint(Graphics g)
{
g.setColor(color[getRandomColor()]);
g.fillOval(x, y, width, height);
}//end paint
}//ball class
public void update(Graphics g)//double buffer don't touch!!
{
if(dbImage == null)
{
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public boolean keyDown (Event e, int key)
{
if(key == Event.LEFT)
{
mainBall.xspeed = -5;
mainBall.yspeed = 0;
}
if(key == Event.RIGHT)
{
mainBall.xspeed = 5;
mainBall.yspeed = 0;
}
if(key == Event.UP)
{
mainBall.yspeed = -5;
mainBall.xspeed = 0;
}
if(key == Event.DOWN)
{
mainBall.yspeed = 5;
mainBall.xspeed = 0;
}
return true;
}
public void run()
{
while(true)
{
repaint();
if (mainBall.xpos < 1)
{
mainBall.xpos = 449;
}
if (mainBall.xpos > 449)
{
mainBall.xpos = 1;
}
if (mainBall.ypos < 1)
{
mainBall.ypos = 449;
}
if (mainBall.ypos > 449)
{
mainBall.ypos = 1;
}
mainBall.ypos += mainBall.yspeed;
mainBall.xpos += mainBall.xspeed;
try
{
Thread.sleep(20);
}
catch(InterruptedException ex){}
}
}
public void init()
{
this.setSize(WIDTH, HEIGHT);
BALLS = new ArrayList<Ball>();
}
public void paint(Graphics g)
{
g.drawString("time: " + t, 20, 20);
mainBall.paintMainBall(g);
for (Ball ball : BALLS)
{
ball.paint(g);
}
updateGame();
}
}
You update the xPos/yPos values of the ball, but never the x/y values
public void paintMainBall(Graphics g) {
System.out.println("PaintMainBall");
g.setColor(Color.RED);
g.fillOval(x, y, width, height);
g.drawString(xpos + ", " + ypos, 20, 40);
}
Related
I have been working on a flappy bird clone so I can get more practice programming. Everything in the game works, however the game has frame skips and lag drops, and I do not know how to make Java programs run more smoothly. Am I supposed to measure the amount of time a method takes and try to shorten that, or do I do something else? I have seen people explain how to program Java games, but there is hardly anything on improving the performance. Any advice would be helpful. Thank you.
Hazards class
package entity;
import java.util.ArrayList;
public class Hazards {
public ArrayList<Horizontal> hors;
public ArrayList<Vertical> verts;
public Hazards(int width, int height, int thickness) {
hors = new ArrayList<Horizontal>();
hors.add(new Horizontal(0, 0, width, thickness));
hors.add(new Horizontal(0, height-thickness, width, thickness));
verts = new ArrayList<Vertical>();
}
}
Horizontal class
package entity;
import java.awt.Rectangle;
public class Horizontal {
public int xPos, yPos, width, height;
public Rectangle bounds;
public Horizontal(int x, int y, int w, int h) {
this.xPos = x;
this.yPos = y;
this.width = w;
this.height = h;
this.bounds = new Rectangle(x, y, w, h);
}
public void updateBounds(int x, int y, int w, int h) {
this.xPos = x;
this.yPos = y;
this.width = w;
this.height = h;
this.bounds = new Rectangle(x, y, w, h);
}
}
Vertical class
package entity;
import java.awt.Rectangle;
import java.util.Random;
public class Vertical {
public int xPos, width, gapSize, gapPos;
public boolean scoredOn = false;
public Rectangle top, bottom;
public Vertical(int xPos, int width, int roofHeight, int floorHeight, int gapSize) {
this.xPos = xPos;
this.width = width;
this.gapPos = new Random().nextInt(floorHeight - gapSize) + roofHeight;
this.top = new Rectangle();
this.bottom = new Rectangle();
this.top.setBounds(xPos, 0, width, gapPos);
this.bottom.setBounds(xPos, gapPos + gapSize, width, floorHeight - roofHeight + top.height + gapSize);
}
}
Content class
package main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JPanel;
public class Content extends JPanel {
private static final long serialVersionUID = 1L;
private Engine e;
private Rectangle bounds;
public Content(Engine engine) {
e = engine;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, this.getWidth(), this.getHeight());
// Roof and floor
g.setColor(Color.black);
for (int x = 0; x < e.e.hors.size(); x++) {
bounds = e.e.hors.get(x).bounds;
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
}
// Pipes
g.setColor(Color.black);
for(int x = 0; x < e.e.verts.size(); x++) {
bounds = e.e.verts.get(x).top;
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
bounds = e.e.verts.get(x).bottom;
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
}
// Player
g.setColor(Color.black);
g.fillRect((int) e.p.xPos, (int) e.p.yPos, e.p.size, e.p.size);
// Score
g.setColor(Color.blue);
g.setFont(new Font("Monospaced", Font.PLAIN, 40));
g.drawString(Integer.toString(e.p.score), e.width/2, 80);
}
}
Engine class
package main;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import entity.Hazards;
import entity.Vertical;
import screen.TitleScreen;
public class Engine implements Runnable {
public JFrame f;
public String title = "Flappy Bird";
public int width = 500, height = 500;
public Content c;
public boolean running = false;
public boolean playing = false;
public Thread t;
public Player p;
public Hazards e;
public TitleScreen ts;
public JPanel mainPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Engine e = new Engine();
e.execute();
}
});
}
public void execute() {
ts = new TitleScreen(width, height);
e = new Hazards(width, height, 30);
p = new Player(this);
c = new Content(this);
c.setPreferredSize(new Dimension(width, height));
c.setLayout(null);
c.addKeyListener(p);
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(width, height));
mainPanel.setLayout(null);
f = new JFrame();
f.setTitle(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(c);
// f.add(mainPanel);
f.pack();
f.createBufferStrategy(2);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setVisible(true);
c.requestFocus();
//ts.setScreen(mainPanel);
start();
}
public synchronized void start() {
if (running)
return;
running = true;
t = new Thread(this);
t.start();
}
public synchronized void stop() {
if (!running)
return;
running = false;
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
long lastime = System.nanoTime();
double AmountOfTicks = 60;
double ns = 1000000000 / AmountOfTicks;
double delta = 0;
int tick = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastime) / ns;
lastime = now;
if (delta >= 1) {
// Call all updates here
if (playing) {
p.updatePos();
tick++;
if (tick == 60) {
tick = 0;
p.distance += p.speed;
System.out.println(p.distance);
if ((p.distance % 4) == 0) {
System.out.println("Making new pipes-----------------------------------------------------");
e.verts.add(new Vertical(600, 10, 30, height - 30, 100));
}
}
for (int x = 0; x < e.verts.size(); x++) {
e.verts.get(x).top.x -= p.speed;
e.verts.get(x).bottom.x -= p.speed;
if(e.verts.get(x).top.x<-50) {
e.verts.remove(x);
System.out.println("removed a pipe");
}
if(p.xPos>e.verts.get(x).top.x && !e.verts.get(x).scoredOn) {
e.verts.get(x).scoredOn = true;
p.score++;
}
}
}
mainPanel.revalidate();
mainPanel.repaint();
f.revalidate();
f.repaint();
delta--;
}
}
}
}
Player class
package main;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener {
public int size = 10;
public double xPos = 50;
public double yPos = 240;
public double gravity = 3.4;
public double jumpForce = 16.6;
public double weight = 1;
public int speed = 2;
public int score = 0;
public int distance = 0;
public boolean jumping = false;
public double jumpTime = 10;
public int timed = 0;
public Rectangle bounds, temp, top, bottom;
public Engine en;
public Player(Engine engine) {
en = engine;
bounds = new Rectangle((int)xPos, (int)yPos, size, size);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W && en.playing) {
jumping = true;
} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
en.playing = !en.playing;
}
if(jumping) {
timed = 0;
jumpForce = 16.6;
}
}
public void keyReleased(KeyEvent e) {
}
public void updatePos() {
// collide with floor or ceiling
for(int x = 0; x < en.e.hors.size(); x++) {
temp = en.e.hors.get(x).bounds;
if(bounds.intersects(temp)) {
en.playing = false;
jumping = false;
timed = 0;
jumpForce = 0;
yPos = 240;
score = 0;
en.e.verts.clear();
distance = 0;
gravity = 3.8;
}
}
// collide with pipe
for(int x =0; x <en.e.verts.size();x++) {
top = en.e.verts.get(x).top;
bottom = en.e.verts.get(x).bottom;
if(bounds.intersects(top)||bounds.intersects(bottom)) {
en.playing = false;
jumping = false;
timed = 0;
jumpForce = 0;
yPos = 240;
score = 0;
gravity =3.4;
en.e.verts.clear();
distance = 0;
}
}
if (jumping && en.playing) {
gravity = 3.4;
yPos -= jumpForce;
jumpForce -= weight;
if (jumpForce == 0) {
jumping = false;
jumpForce = 16.6;
}
}
//if(!jumping && en.playing) {
gravity += 0.1;
//}
System.out.println(gravity);
yPos += gravity;
bounds.setBounds((int)xPos, (int)yPos, size, size);
}
}
I'm in despair, because my animation isn't as smooth as I expected. So I know, there is a lot of stuff around this problem, but mine is different in that way, that I know the common problems and I think, I'm doing it right. So firstly, this is my code:
Game.java
import de.lwerner.collisions.CircleCollision;
import de.lwerner.collisions.math.Vector2D;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class Game extends JPanel implements ActionListener {
private static final Color BACKGROUND_COLOR = new Color(0, 0, 25);
private static final Color TEXT_COLOR = Color.WHITE;
private static final int TARGET_FPS = 60;
private javax.swing.Timer swingTimer;
private JFrame window;
private Timer timer;
private Timer fpsTimer;
private int counter;
private long[] diffs;
private int fps;
private LinkedList<Circle> circles;
private LinkedList<Sprite> sprites;
public Game() {
timer = new Timer();
fpsTimer = new Timer(System.currentTimeMillis());
diffs = new long[TARGET_FPS];
circles = new LinkedList<>();
circles.add(new Circle(100, 100, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(250, 250, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(400, 400, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(550, 550, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(700, 700, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(100, 700, 50, -300, 300, Color.WHITE));
// circles.add(new Circle(250, 550, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(550, 250, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(700, 100, 50, -300, 300, Color.WHITE));
sprites = new LinkedList<>();
sprites.addAll(circles);
window = new JFrame("Game");
window.setContentPane(this);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setUndecorated(true);
window.setResizable(false);
window.validate();
window.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
stop();
}
});
window.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
stop();
}
});
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(window);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Sprite s: sprites) {
s.render(g);
}
g.setColor(TEXT_COLOR);
g.drawString(fps + " FPS", 10, 20);
diffs[counter % TARGET_FPS] = fpsTimer.tick();
if (++counter % TARGET_FPS == 0) {
int sum = 0;
for (long diff: diffs) {
sum += diff;
}
fps = 1000 / (sum / TARGET_FPS);
}
}
private void step() {
long tick = timer.tick();
for (Sprite s: sprites) {
s.update(tick);
}
repaint();
checkCollisions();
}
private void checkCollisions() {
for (Sprite s1: sprites) {
BoundingBox bb = s1.getBoundingBox();
int offset = 0;
if (s1 instanceof Circle) {
offset = ((Circle) s1).getRadius();
}
if (bb.getLeft() < 0 || bb.getRight() >= getWidth()) {
s1.setVelX(-s1.getVelX());
if (bb.getLeft() < 0) {
s1.setX(0 + offset);
} else {
s1.setX(getWidth() - 1 - offset);
}
}
if (bb.getTop() < 0 || bb.getBottom() >= getHeight()) {
s1.setVelY(-s1.getVelY());
if (bb.getTop() < 0) {
s1.setY(0 + offset);
} else {
s1.setY(getHeight() - 1 - offset);
}
}
}
// Set<Set<Circle>> collidingPairs = new HashSet<>();
// for (Circle c1: circles) {
// for (Circle c2: circles) {
// if (c1 == c2) {
// continue;
// } else {
// if (c1.intersects(c2)) {
// Set<Circle> pair = new HashSet<>(Arrays.asList(c1, c2));
// if (!collidingPairs.contains(pair)) {
// collidingPairs.add(pair);
// de.lwerner.collisions.Circle cc1 = new de.lwerner.collisions.Circle(c1.getX(), c1.getY(), c1.getRadius(), new Vector2D(c1.getVelX(), c1.getVelY()));
// de.lwerner.collisions.Circle cc2 = new de.lwerner.collisions.Circle(c2.getX(), c2.getY(), c2.getRadius(), new Vector2D(c2.getVelX(), c2.getVelY()));
// CircleCollision collision = new CircleCollision(cc1, cc2);
// collision.resolveCollision();
// Vector2D v1New = cc1.getV();
// Vector2D v2New = cc2.getV();
// c1.setVelX((int) v1New.getX());
// c1.setVelY((int) v1New.getY());
// c2.setVelX((int) v2New.getX());
// c2.setVelY((int) v2New.getY());
// }
// }
// }
// }
// }
}
private void stop() {
if (swingTimer.isRunning()) {
swingTimer.stop();
window.dispose();
}
}
public void start() {
swingTimer = new javax.swing.Timer(1000 / TARGET_FPS, this);
swingTimer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Game().start());
}
}
Sprite.java
import java.awt.*;
public abstract class Sprite {
protected double x;
protected double y;
protected int width;
protected int height;
protected int velX;
protected int velY;
public Sprite(int x, int y, int width, int height) {
this(x, y, width, height, 0, 0);
}
public Sprite(int x, int y, int width, int height, int velX, int velY) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velX = velX;
this.velY = velY;
}
public int getX() {
return (int)Math.round(x);
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return (int)Math.round(y);
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}
public void update(long tick) {
x += tick * velX / 1000.0;
y += tick * velY / 1000.0;
}
public BoundingBox getBoundingBox() {
return new BoundingBox(getY(), getX() + width, getY() + height, getX());
}
public boolean intersects(Sprite other) {
return getBoundingBox().intersects(other.getBoundingBox());
}
public abstract void render(Graphics g);
}
Circle.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Circle extends Sprite {
private Color color;
private BufferedImage image;
public Circle(int x, int y, int r, Color c) {
super(x, y, r * 2, r * 2);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
public Circle(int x, int y, int r, int velX, int velY, Color c) {
super(x, y, r * 2, r * 2, velX, velY);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
private void loadImage() throws IOException {
image = ImageIO.read(getClass().getResource("/bubble.png"));
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getRadius() {
return width / 2;
}
public boolean intersects(Circle other) {
int dx = Math.abs(getX() - other.getX());
int dy = Math.abs(getY() - other.getY());
int r1 = getRadius();
int r2 = other.getRadius();
return dx * dx + dy * dy < (r1 + r2) * (r1 + r2);
}
#Override
public BoundingBox getBoundingBox() {
return new BoundingBox(getY() - getRadius(), getX() + getRadius(), getY() + getRadius(), getX() - getRadius());
}
#Override
public void render(Graphics g) {
if (image == null) {
g.setColor(color);
g.fillOval(getX() - getRadius(), getY() - getRadius(), width, height);
} else {
g.drawImage(image, getX() - getRadius(), getY() - getRadius(), null);
}
}
}
Timer.java
public class Timer {
private long lastTime;
public Timer() {
this(0L);
}
public Timer(long initialTime) {
lastTime = initialTime;
}
public long tick() {
if (lastTime == 0) {
lastTime = System.currentTimeMillis();
return 0;
}
long current = System.currentTimeMillis();
long diff = current - lastTime;
lastTime = current;
return diff;
}
}
BoundingBox.java
import java.awt.*;
public class BoundingBox {
private int top;
private int right;
private int bottom;
private int left;
public BoundingBox(int top, int right, int bottom, int left) {
this.top = top;
this.right = right;
this.bottom = bottom;
this.left = left;
}
public int getTop() {
return top;
}
public int getRight() {
return right;
}
public int getBottom() {
return bottom;
}
public int getLeft() {
return left;
}
public Rectangle getRectangle() {
return new Rectangle(left, top, right - left, bottom - top);
}
public boolean intersects(BoundingBox other) {
return getRectangle().intersects(other.getRectangle());
}
#Override
public String toString() {
return "BoundingBox{" +
"top=" + top +
", right=" + right +
", bottom=" + bottom +
", left=" + left +
'}';
}
}
So I don't know, what I'm doing wrong. Common problems such as calling paint(), using not-doublebuffered components, using wrong methods for periodically run code and so on aren't present, yet it's flickering. The FPS are constant.
So, please help me! I'd be very glad to come over this...
Thanks!
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.
i have looked all over the internet and in my school books but I can't seem to slove my problem.
In my program "bouncing ball" (got the code from our teacher) i need to change the size of the ball from small to bigger and reverse. I understand that i need a boolean to do that and maybe alsow an if statment. This is what I have in the Ball class rigth now regarding the size change:
private boolean changeSize = true;
int maxSize = 10;
int minSize = 1;
public void changeSize(boolean size ){
if(size == maxSize ){
return minSize;
}
else return maxSize;
}
public void changeBallSize(int d, int f){
diameter = d*f;
This is the whole code for the class Ball:
class Ball {
static int defaultDiameter = 10;
static Color defaultColor = Color.yellow;
static Rectangle defaultBox = new Rectangle(0,0,100,100);
// Position
private int x, y;
// Speen and angel
private int dx, dy;
// Size
private int diameter;
// Color
private Color color;
// Bouncing area
private Rectangle box;
// New Ball
public Ball( int x0, int y0, int dx0, int dy0 ) {
x = x0;
y = y0;
dx = dx0;
dy = dy0;
color = defaultColor;
diameter = defaultDiameter;
}
// New color
public void setColor( Color c ) {
color = c;
}
public void setBoundingBox( Rectangle r ) {
box = r;
}
// ball
public void paint( Graphics g ) {
// Byt till bollens färg
g.setColor( color );
g.fillOval( x, y, diameter, diameter );
}
void constrain() {
// Ge absoluta koordinater för det rektangulära området
int x0 = box.x;
int y0 = box.y;
int x1 = x0 + box.width - diameter;
int y1 = y0 + box.height - diameter;
// Setting speed and angels
if (x < x0)
dx = Math.abs(dx);
if (x > x1)
dx = -Math.abs(dx);
if (y < y0)
dy = Math.abs(dy);
if (y > y1)
dy = -Math.abs(dy);
}
// movingt the ball
x = x + dx;
y = y + dy;
constrain();
}
}
I am a total rookie of java! Thanks for the help!
Add the following into your Ball class:
private int changeFlag=-1;
In your constrain() function, just before the last line, after moving the ball:
if(diameter==maxSize) {
changeFlag=-1;
}
else if (diameter==minSize) {
changeFlag=1;
}
diameter=diameter+changeFlag;
Add this code to your Ball Class
private minSize = 1;
private maxSize = 10;
public void setDiameter(int newDiameter) {
this.diameter = newDiameter;
}
public int getMinSize() {
return minSize;
}
public int getMinSize() {
return maxSize;
}
Use this when you use the ball
Ball ball = new Ball(1,1,1,1);
int newDiameter = 10;
if(newDiameter == ball.getMinSize()) {
ball.setDiameter(ball.getMaxSize());
}
id(newDiameter == ball.getMaxSize()) {
ball.setDiameter (ball.getMinSize());
}
I've edited it, is this what you mean?
Main Class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
// configure JFrame
setSize(640, 360);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create ball
Ball ball = new Ball(this.getWidth()/2, this.getHeight()/2, 50, 100);
add(ball);
Thread t = new Thread(ball);
t.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
}
}
Ball Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
public class Ball extends JComponent implements Runnable {
private int x, y, minDiameter, maxDiameter, currentDiameter, growRate = -1;
private Color color = Color.BLUE;
public Ball(int x, int y, int minDiameter, int maxDiameter) {
this.x = x;
this.y = y;
this.minDiameter = minDiameter;
this.maxDiameter = maxDiameter;
this.currentDiameter = minDiameter;
setVisible(true);
}
#Override
public void run() {
while (true) {
// coerce max and min size
if (this.currentDiameter + growRate > maxDiameter) {
this.currentDiameter = maxDiameter;
this.growRate = -1;
}
if (this.currentDiameter + growRate < minDiameter) {
this.currentDiameter = minDiameter;
this.growRate = 1;
}
this.currentDiameter += this.growRate;
repaint();
try {
Thread.sleep(10);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2.setColor(this.color);
g2.fillOval(this.x, this.y, this.currentDiameter, this.currentDiameter);
}
}
I wrote a game in Java and I want to put it on a HTML page. I know how, but the problem is that it gives me a AcessControlException (java.io.FilePermission "/SomePath/SomeFile.SomeExtension" "read").
Here is the Game class (loads the files at initGame method and init the JApplet):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.swing.JApplet;
public class Game extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
private Thread thread;
public static BufferedImage level;
public static BufferedImage background;
public static Image2d tileset;
public static Sprite red;
public static Sprite green;
public static Sprite player;
public static boolean mouse_left, mouse_right;
public static boolean jumping;
public static boolean play;
private boolean running = false;
private Image screen;
public static RandomLevel map;
public static Listener listener;
public static Gui gui;
public static int FALL_SPEED = 3;
public static int JUMP_SPEED = 3;
public static int JUMP_HEIGHT = 20;
public static int jump_amount = 0;
public static float START_OFFSET_SPEED = 3.0f;
public static float OFFSET_SPEED = 2.0f;
public static final int sxOffset = 0, syOffset = 0;
public static int xOffset = 0, yOffset = 0;
public static final int CURR_COLOR_SCALE = 32;
public static Sprite[] tiles = new Sprite[2];
public static int selected_color = 0;
public static int SCORE = 0;
public static final int TILE_SIZE = 16;
public static final int SCALE = TILE_SIZE * 2;
public static boolean left, right;
public static int currTime = 0;
public static final Dimension size = new Dimension(800, 600);
public static final Dimension pixel = new Dimension(size.width - SCALE, size.height - SCALE);
public void initGame() {
try {
URL levelUrl = new URL(getCodeBase(), "res/map.png");
level = new Image2d(levelUrl).getImage();
URL backgroundUrl = new URL(getCodeBase(), "res/background.png");
background = new Image2d(backgroundUrl).getImage();
URL tilesetUrl = new URL(getCodeBase(), "res/tileset.png");
tileset = new Image2d(tilesetUrl);
} catch (IOException e) {
}
red = new Sprite(new Image2d(tileset.crop(0, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
green = new Sprite(new Image2d(tileset.crop(1, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
player = new Sprite(new Image2d(tileset.crop(2, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
tiles[0] = red;
tiles[1] = green;
gui = new Gui();
listener = new Listener();
player.setX((size.width - player.getImage().getWidth(null)) / 2);
player.setY((size.height - player.getImage().getHeight(null)) / 2 + 100);
map = new RandomLevel(10000, 20, TILE_SIZE, SCALE, size, xOffset, yOffset);
map.addCollsion(tiles[0]);
addMouseListener(listener);
addMouseMotionListener(new Mouse());
}
public static void switchCollision(Sprite tile) {
map.collision.add(0, tile);
for (int i = 0; i < map.collision.size(); i++) {
if (i != 0)
map.collision.remove(i);
}
}
public void resetGame() {
xOffset = sxOffset;
yOffset = syOffset;
OFFSET_SPEED = START_OFFSET_SPEED;
Game.SCORE = 0;
play = false;
map.generateLevel();
}
public void startGame() {
if (running)
return;
initGame();
running = true;
thread = new Thread(this);
thread.start();
}
public void stopGame() {
if (!running)
return;
running = true;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
screen = createVolatileImage(pixel.width, pixel.height);
requestFocus();
while (running) {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
update();
delta--;
}
render();
if (System.currentTimeMillis() - timer > 100) {
timer += 1000;
}
}
stop();
}
}
public void update() {
if (!play && mouse_left)
play = true;
if (play) {
switchCollision(tiles[selected_color]);
if (yOffset > 180)
resetGame();
map.update();
map.setxOffset(xOffset);
map.setyOffset(yOffset);
player.update(25);
gui.update();
if (!map.getTileDownCollision(player))
yOffset += FALL_SPEED;
if (!Game.map.getTileRightCollision(player))
xOffset += Math.round(OFFSET_SPEED);
if (SCORE > 20)
OFFSET_SPEED = 4.0f;
if (SCORE > 40)
OFFSET_SPEED = 5.0f;
if (SCORE > 60)
OFFSET_SPEED = 6.0f;
if (SCORE > 80)
OFFSET_SPEED = 7.0f;
if (SCORE > 100)
OFFSET_SPEED = 8.0f;
if (SCORE > 120)
OFFSET_SPEED = 9.0f;
if (SCORE > 140)
OFFSET_SPEED = 10.0f;
if (jumping) {
FALL_SPEED = 0;
yOffset -= JUMP_SPEED;
jump_amount++;
if (jump_amount >= JUMP_HEIGHT) {
jumping = false;
FALL_SPEED = 3;
jump_amount = 0;
}
}
}
}
public void render() {
Graphics g = screen.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, size.width, size.height);
map.render(g);
g.drawImage(player.getImage(), Math.round(player.getX()), Math.round(player.getY()), Game.TILE_SIZE + Game.SCALE, Game.TILE_SIZE + Game.SCALE, null);
g.setFont(new Font("new Font", Font.PLAIN, 10));
g.setColor(Color.white);
g.drawString("CLICK ON THIS SIDE TO JUMP", 200 - xOffset, 240);
g.drawString("CLICK ON THIS SIDE TO SWITCH COLOR", size.width - 350 - xOffset, 240);
g.drawImage(background, 0, 0, null);
g.drawImage(map.collision.get(0).getImage(), (size.width - (Game.TILE_SIZE + CURR_COLOR_SCALE)) / 2, CURR_COLOR_SCALE / 2 - 5, Game.TILE_SIZE + CURR_COLOR_SCALE, Game.TILE_SIZE + CURR_COLOR_SCALE, null);
gui.render(g);
g.setFont(new Font("new Font", Font.BOLD, 32));
g.setColor(Color.yellow);
g.drawString("SCORE: " + SCORE, 10, 32);
g = getGraphics();
g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null);
g.dispose();
}
public void destroy() {
System.exit(0);
}
public void init() {
setSize(size);
setVisible(true);
startGame();
}
}
EDIT: Here is the Image2d class(holds ImageIO.read command)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Image2d{
private BufferedImage image;
public Image2d(URL url) {
try {
image = ImageIO.read(url);
} catch (IOException e) {
System.err.println("No file found at: " + url);
}
}
public Image2d(String path) {
try {
image = ImageIO.read(new File(path));
} catch (IOException e) {
System.err.println("No file found at: " + path);
}
}
public static BufferedImage load(URL url) {
try {
return ImageIO.read(url);
} catch (IOException e) {
System.err.println("No file found at: " + url.getPath());
return null;
}
}
public static BufferedImage load(String path) {
try {
return ImageIO.read(new File(path));
} catch (IOException e) {
System.err.println("No file found at: " + path);
return null;
}
}
public Image2d(BufferedImage image) {
this.image = image;
}
public BufferedImage crop(int x, int y, int w, int h) {
return image.getSubimage(x * w, y * h, w, h);
}
public static BufferedImage insert(Image2d target, Image2d component) {
BufferedImage tile = new BufferedImage(target.getImage().getWidth(), target.getImage().getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = tile.getGraphics();
g.drawImage(component.getImage(), 0, 0, component.getImage().getWidth(), component.getImage().getHeight(), null);
g.drawImage(target.getImage(), 0, 0, target.getImage().getWidth(), target.getImage().getHeight(), null);
return tile;
}
public static BufferedImage switchColor(BufferedImage image, Color color1, Color color2) {
Graphics g = image.getGraphics();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = new Color(image.getRGB(x, y));
if (color.getRed() == color1.getRed() && color.getGreen() == color1.getGreen() && color.getBlue() == color1.getBlue() && color.getAlpha() == color1.getAlpha()) {
g.setColor(color2);
g.fillRect(x, y, 1, 1);
}
}
}
return image;
}
public static BufferedImage fill(Color color, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, width, height);
return image;
}
public static BufferedImage switchColor(BufferedImage image, Color[] color1, Color[] color2) {
Graphics g = image.getGraphics();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = new Color(image.getRGB(x, y));
for (int i = 0; i < color1.length; i++)
if (color.getRed() == color1[i].getRed() && color.getGreen() == color1[i].getGreen() && color.getBlue() == color1[i].getBlue() && color.getAlpha() == color1[i].getAlpha()) {
g.setColor(color2[i]);
g.fillRect(x, y, 1, 1);
}
}
}
return image;
}
public static BufferedImage createYDropShadow(int width, int height, int startAlpha, float density, float offset, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
int alpha = startAlpha;
for (int y = 0; y < image.getHeight(); y++) {
if (alpha >= density)
alpha -= density;
for (int x = 0; x < image.getWidth(); x++) {
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
g.fillRect(x + Math.round(offset), y + Math.round(offset), 1 + Math.round(offset), 1 + Math.round(offset));
}
}
return image;
}
public static BufferedImage createXDropShadow(int width, int height, int startAlpha, float density, float offset, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
int alpha = startAlpha;
for (int x = 0; x < image.getWidth(); x++) {
if (alpha >= density)
alpha -= density;
for (int y = 0; y < image.getHeight(); y++) {
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
g.fillRect(x + Math.round(offset), y + Math.round(offset), 1 + Math.round(offset), 1 + Math.round(offset));
}
}
return image;
}
public BufferedImage getImage() {
return image;
}
}
And here is html code (it is inside a jar file called Blocks.jar):
<!DOCTYPE html>
<html>
<body>
<applet code="Game.class" archive="Blocks.jar" width="600" height="600"> </applet>
</body>
</html>
I saw people getting the same error but, no answer gave me a solution that worked. So what shoud I do for load the images without erros?
PS: The JApplet is running fine in eclipse, but at the html page throws me this error.
Thanks!