So I'm having this issue with my game that I'm working on for practice and one of the things that I'm struggling with is having this random color change between these four colors red, green, blue, yellow. My objective is to have this ball bounce around the screen while changing between the four colors but I would like to have a delay or pause in between the swapping of the colors like for at least 3 or 5 seconds. So far in the code the ball seems to change but without delay I've tried using a few delay methods like Timer.Schedule but eveytime I use this the ball bounces around the screen but its all black and no color I would really appreciate any help? I felt silly asking a question like this because I have a feeling it may be a small issue.
public class Play implements Screen {
Game game;
private Rectangle field = new Rectangle();
private Ball ball = new Ball();
private Paddle paddle1 = new Paddle(), paddle2 = new Paddle();
private ShapeRenderer ballRenderer, paddleRenderer;
private float fieldTop, fieldBottom, fieldRight, fieldLeft;
private Color ballColor = new Color();
private Random rnd = new Random();
public Play(Game game){
this.game = game;
}
#Override
public void render(float delta) {
float dt = Gdx.graphics.getRawDeltaTime();
update(dt);
draw(dt);
}
private void update(float dt) {
updateBall(dt);
updatepaddle1(dt);
}
private void updatepaddle1(float dt) {
boolean moveLeft = false, moveRight = false;
if(Gdx.input.isTouched()){
moveLeft = true;
moveRight = false;
}
if(Gdx.input.isTouched()){
moveRight = true;
moveLeft = false;
}
if(moveRight){
paddle1.setVelocity(350f, 0f);
}else if(moveLeft){
paddle1.setVelocity(-350f, 0f);
}else{
paddle1.setVelocity(0, 0);
}
paddle1.Intergrate(dt);
}
private void updateBall(float dt) {
// TODO Auto-generated method stub
ball.Intergrate(dt);
ball.updateBounds();
if(ball.left() < fieldLeft){
ball.move(fieldLeft, ball.getY());
ball.reflect(true, false);
}
if(ball.right() > fieldRight){
ball.move(fieldRight - ball.getWidth(), ball.getVelocityX());
ball.reflect(true, false);
}
if(ball.bottom() < fieldBottom){
ball.move(ball.getX(), fieldBottom);
ball.reflect(false, true);
}
if(ball.top() > fieldTop){
ball.move(ball.getX(), fieldTop - ball.getHeight());
ball.reflect(false, true);
}
}
public void reset(){
ball.move(field.x + (field.width - ball.getWidth()) / 2, field.y + (field.height - ball.getHeight()) / 2);
Vector2 velocity = ball.getVelocity();
velocity.set(330f, 0f);
velocity.setAngle(360f-45f);
ball.setVelocity(velocity);
//set paddle
paddle1.move(field.x + (field.width * .4f), 0);
paddle2.move(field.x + (field.width * .4f), field.y + (field.height - paddle1.getHeight()));
}
private void draw(float dt) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
paddleRenderer.begin(ShapeType.Filled);
drawPaddles(dt);
paddleRenderer.end();
ballRenderer.begin(ShapeType.Filled);
ballColorSwap(ballColor);
drawBall(dt);
ballRenderer.end();
}
private void drawPaddles(float dt) {
paddleRenderer.rect(paddle1.getX(), paddle1.getY(), paddle1.getWidth(), paddle1.getHeight());
paddleRenderer.rect(paddle2.getX(), paddle2.getY(), paddle2.getWidth(), paddle2.getHeight());
}
int THRESHOLD = 4000;
long lastChanged = 0;
private void ballColorSwap(Color ballColor){
int rnd = (int)(Math.random() * 4);
if(rnd == 1){
ballColor.set(Color.RED);
}
if(rnd == 2){
ballColor.set(Color.BLUE);
}
if(rnd == 3){
ballColor.set(Color.GREEN);
}
if(rnd == 4){
ballColor.set(Color.YELLOW);
}
lastChanged = System.currentTimeMillis();
}
private void drawBall(float dt) {
if(System.currentTimeMillis() - lastChanged > THRESHOLD)
ballColorSwap(ballColor);
ballRenderer.circle(ball.getX(), ball.getY(), 20);
ballRenderer.setColor(ballColor);
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
field.set(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
fieldLeft = field.x;
fieldRight = field.x + field.width;
fieldBottom = field.y;
fieldTop = field.y + field.height;
paddleRenderer = new ShapeRenderer();
ballRenderer = new ShapeRenderer();
reset();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Can you just add one more variable to save a timestamp?
int THRESHOLD = 4000; // 4 seconds
long lastChanged = 0; // timestamp
public void ballColorSwap(){
// maybe call it here?
if(System.currentTimeMillis() - lastChanged < THRESHOLD)
return;
int rnd = (int)(Math.random() * 4);
if(rnd == 1){
ballColor.set(Color.RED);
}
if(rnd == 2){
ballColor.set(Color.BLUE);
}
if(rnd == 3){
ballColor.set(Color.GREEN);
}
if(rnd == 4){
ballColor.set(Color.YELLOW);
}
// set the timestamp
lastChanged = System.currentTimeMillis();
}
private void drawBall(float dt) {
ballRenderer.circle(ball.getX(), ball.getY(), 20);
ballRenderer.setColor(ballColor);
}
Note: I haven't tested this code. It might need some modification but hope you get the idea.
Related
I am making a game with android. The player is a rectangle that has to jump over obstacles. When i jump i decrease the height and the y coordinates. When i run the game the rectangle is jumping but when i try to jump over an obstacle its still hitting it. So i think i forget to change a value but i have no idea what value. Sorry for my bad english and i am a beginner at coding.
This is my Player class:
package com.example.niek.speelveld;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Created by Niek on 15-8-2017.
*/
public class Player extends GameObject {
private int score;
private boolean up;
private boolean playing;
private long startTime;
private int h = 0;
private boolean jump;
public Player(int x , int y){
super.x = x;
super.y = y;
width = 100;
height = GamePanel.HEIGHT;
score = 0;
startTime = System.nanoTime();
}
public void setUp(boolean b){up = b;}
public void update(){
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>100){
score++;
startTime = System.nanoTime();
}
if(up && h == 0){
jump = true;
up = false;
}
if (jump) {
if (h < 120) {
h = h + 7;
height = height - 7;
y = y - 7;
} else {
jump = false;
}
} else {
if (h > 0) {
h = h - 7;
height = height + 7;
y = y + 7;
}
}
}
public void draw(Canvas canvas){
Paint myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(7);
canvas.drawRect(x, y, width + x, height, myPaint );
myPaint.setStrokeWidth(1);
canvas.drawText("HIGHSCORE " + score, GamePanel.WIDTH - 100 , 0+myPaint.getTextSize(), myPaint);
}
public int getScore(){return score;}
public boolean getPlaying(){return playing;}
public void setPlaying(boolean b){playing = b;}
//public void resetScore(){score = 0;}
public boolean getJump() {
return jump;
}
}
And in my Gamepanel class i use these 2 methods. When i call the class obstacle.get(i).update(); its only updating the x value so its moving towards the player.
public void update(){
if(player.getPlaying()) {
bg.update();
player.update();
//Add obstacles with timer
long obstacleElapsed = (System.nanoTime()-obstacleStartTime)/1000000;
if(obstacleElapsed >(2000 - player.getScore()/4)){
obstacles.add(new Obstacle(BitmapFactory.decodeResource(getResources(), R.drawable.rsz_spike1), WIDTH + 10, HEIGHT - 51, 14, 51, player.getScore()));
//reset timer
obstacleStartTime = System.nanoTime();
}
}
//Loop through every obstacle and check collision
for(int i = 0; i<obstacles.size(); i++){
obstacles.get(i).update();
if (collision(obstacles.get(i), player)) {
obstacles.remove(i);
player.setPlaying(false);
Intent intent = new Intent(c, Result.class);
intent.putExtra("SCORE", player.getScore());
c.startActivity(intent);
break;
}
//Remove obstacles that are out of the screen
if (obstacles.get(i).getX() < -100) {
obstacles.remove(i);
break;
}
}
}
public boolean collision(GameObject o, GameObject p){
if(Rect.intersects(o.getRectangle(), p.getRectangle())){
return true;
}
return false;
}
#Override
public void draw(Canvas canvas){
//Get Width and Height from screen
final float scaleFactorX = (float)getWidth()/WIDTH;
final float scaleFactorY = (float)getHeight()/HEIGHT;
if(canvas!=null) {
final int savedState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
bg.draw(canvas);
player.draw(canvas);
//Draw obstacles
for(Obstacle o : obstacles ){
o.draw(canvas);
}
canvas.restoreToCount(savedState);
}
}
And finally the Player and the Obstacle class extends Gameobject where i have the getRectangle method.
public Rect getRectangle(){
return new Rect(x, y, x+width, y+height);
}
So I've been having some trouble with positioning the "camera" on the player since this is my first time trying to accomplish this. Whenever I launch my game and I move my player, the camera doesn't seem to center on the player like I hope it to do and I don't know what is wrong with it. I've tried looking through online resources and checked out many questions on stack overflow but I could not find what I did wrong :/ . I am using Java and using the Slick2D engine. Here are my class files:
Camera.class:
private float offsetMaxX;
private float offsetMaxY;
private float offsetMinX = 0;
private float offsetMinY = 0;
public float camX;
public float camY;
public Camera () {
super ();
}
public void update (float playerX, float playerY, float mapX, float mapY){
offsetMaxX = mapX - Main.WIDTH;
offsetMaxY = mapY - Main.HEIGHT;
camX = playerX - Main.WIDTH/2;
camY = playerY - Main.HEIGHT/2;
if (camX > offsetMaxX) {
camX = offsetMaxX;
} else if (camX < offsetMinX) {
camX = offsetMinX;
}
if (camY > offsetMaxY) {
camY = offsetMaxY;
} else if (camY < offsetMinY) {
camY = offsetMinY;
}
}
public float getCamX() {
return camX;
}
public float getCamY() {
return camY;
}
public float getOffsetMaxX() {
return offsetMaxX;
}
public float getOffsetMaxY() {
return offsetMaxY;
}
public float getOffsetMinX() {
return offsetMinX;
}
public float getOffsetMinY() {
return offsetMinY;
}
public void setOffsetMaxX(float offsetMaxX) {
this.offsetMaxX = offsetMaxX;
}
public void setOffsetMaxY(float offsetMaxY) {
this.offsetMaxY = offsetMaxY;
}
public void setOffsetMinX(float offsetMinX) {
this.offsetMinX = offsetMinX;
}
public void setOffsetMinY(float offsetMinY) {
this.offsetMinY = offsetMinY;
}
And my Game.class:
// Player variables
public SpriteSheet playerSS = null;
protected InputHandler inputHandler;
public float playerX = Main.WIDTH/2, playerY = Main.HEIGHT/2;
private Animation sprite, runningAnimationLEFT, runningAnimationRIGHT, runningAnimationUP, runningAnimationDOWN;
private Animation standLEFT, standRIGHT, standUP, standDOWN; //THIS IS TO PREVENT ANIMATIONS FROM CONTINUING AFTER THE PLAYER STOPS
private int duration = 300;
public boolean isMoving, isLeft, isRight, isUp, isDown;
//Map
private Image testMap; //This is a test map
private float mapX = 1024, mapY = 1024;
//Camera
public Camera camera;
public Game (int stateID) {}
#Override
public int getID() {
return Main.game; //GAMESTATE = 1
}
#Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
playerSS = new SpriteSheet("res/characters/player_sprite_sheet.png", 50, 75);
testMap = new Image ("res/grassMap.png");
camera = new Camera();
// ANIMATIONS
runningAnimationDOWN = new Animation();
runningAnimationDOWN.setAutoUpdate(true);
runningAnimationDOWN.addFrame(playerSS.getSprite(1, 0), duration);
runningAnimationDOWN.addFrame(playerSS.getSprite(0, 0), duration);
runningAnimationDOWN.addFrame(playerSS.getSprite(2, 0), duration);
runningAnimationLEFT = new Animation();
runningAnimationLEFT.setAutoUpdate(true);
runningAnimationLEFT.addFrame(playerSS.getSprite(1, 1), duration);
runningAnimationLEFT.addFrame(playerSS.getSprite(0, 1), duration);
runningAnimationLEFT.addFrame(playerSS.getSprite(2, 1), duration);
runningAnimationRIGHT = new Animation();
runningAnimationRIGHT.setAutoUpdate(true);
runningAnimationRIGHT.addFrame(playerSS.getSprite(1, 2), duration);
runningAnimationRIGHT.addFrame(playerSS.getSprite(0, 2), duration);
runningAnimationRIGHT.addFrame(playerSS.getSprite(2, 2), duration);
runningAnimationUP = new Animation();
runningAnimationUP.setAutoUpdate(true);
runningAnimationUP.addFrame(playerSS.getSprite(1, 3), duration);
runningAnimationUP.addFrame(playerSS.getSprite(0, 3), duration);
runningAnimationUP.addFrame(playerSS.getSprite(2, 3), duration);
standDOWN = new Animation();
standDOWN.setAutoUpdate(true);
standDOWN.addFrame(playerSS.getSprite(1, 0), duration);
standLEFT = new Animation();
standLEFT.setAutoUpdate(true);
standLEFT.addFrame(playerSS.getSprite(1, 1), duration);
standRIGHT = new Animation();
standRIGHT.setAutoUpdate(true);
standRIGHT.addFrame(playerSS.getSprite(1, 2), duration);
standUP = new Animation();
standUP.setAutoUpdate(true);
standUP.addFrame(playerSS.getSprite(1, 3), duration);
sprite = standDOWN;
}
#Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
inputHandler.updateKeyboardRelay(gameContainer);
isMoving = false;
if (inputHandler.keyUP) {
isUp = true;
isDown = false;
isLeft = false;
isRight = false;
isMoving = true;
playerY -= delta * 0.1f;
} else if (inputHandler.keyDOWN) {
isDown = true;
isUp = false;
isLeft = false;
isRight = false;
isMoving = true;
playerY += delta * 0.1f;
} else if (inputHandler.keyLEFT) {
isLeft = true;
isUp = false;
isDown = false;
isRight = false;
isMoving = true;
playerX -= delta * 0.1f;
} else if (inputHandler.keyRIGHT) {
isRight = true;
isUp = false;
isDown = false;
isLeft = false;
isMoving = true;
playerX += delta * 0.1f;
}
if (isMoving) {
if (inputHandler.keyUP) {
sprite = runningAnimationUP;
sprite.update(delta);
} else if (inputHandler.keyDOWN) {
sprite = runningAnimationDOWN;
sprite.update(delta);
} else if (inputHandler.keyLEFT) {
sprite = runningAnimationLEFT;
sprite.update(delta);
} else if (inputHandler.keyRIGHT) {
sprite = runningAnimationRIGHT;
sprite.update(delta);
}
} else {
if (isDown) {
sprite = standDOWN;
sprite.update(delta);
} else if (isUp) {
sprite = standUP;
sprite.update(delta);
} else if (isLeft) {
sprite = standLEFT;
sprite.update(delta);
} else if (isRight) {
sprite = standRIGHT;
sprite.update(delta);
}
}
// Map Boundaries
if (playerX > mapX) {
playerX = mapX;
} else if (playerX < 0) {
playerX = 0;
}
if (playerY > mapY) {
playerY = mapY;
} else if (playerY < 0) {
playerY = 0;
}
camera.update(playerX, playerY, mapX, mapY);
}
#Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
testMap.draw(mapX - 1024, mapY - 1024);
graphics.translate(camera.getCamX(), camera.getCamY());
sprite.draw(playerX, playerY);
graphics.translate(-camera.getCamX(), -camera.getCamY());
graphics.drawString("Player X: " + playerX, 400, 400);
graphics.drawString("Player Y: " + playerY, 400, 415);
}
I feel like there is something specifically wrong in my Camera.class and my update(...) & render(...) methods, but I don't know what.
Here in your camera class in the update method try changing
camX = playerX - Main.WIDTH/2;
camY = playerY - Main.HEIGHT/2;
to
camX = playerX;
camY = playerY;
tell me if this does not work.
I'm new to Java graphics and threads, and I'm trying to make a game (specifically, Pong). The idea is that two people can play on the same keyboard (i.e. there are two paddles that are controlled through different keys). Currently, both players can't move their paddle at the same time.
Is there a solution to this? Are separate threads the answer?
If possible, I'd like the paddles to be able to move (at least seemingly) at the same time.
Update: It seems like using a Set<Integer> to store pressed keys is the best option. I've done that (and it works), but I'm wondering if any of this code is not on the Event Dispatching Thread (EDT) and if I need to use SwingUtilities.invokeLater();. Here's the necessary code:
private Set<Integer> keysDown = Collections.synchronizedSet(new HashSet<Integer>());
public void keyPressed(KeyEvent e)
{
keysDown.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e)
{
keysDown.remove(e.getKeyCode());
}
public void updatePaddlePositions()
{
if (keysDown.contains(KeyEvent.VK_W))
paddleOne.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_S))
paddleOne.move(PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_UP))
paddleTwo.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_DOWN))
paddleTwo.move(PADDLE_MOVE_INCREMENT);
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("You Interrupted the game!");
}
canvas.repaint();
}
Here's the paintComponent method of the canvas object:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paddleOne.paint(g);
paddleTwo.paint(g);
updatePaddlePositions(); // Does this need to be SwingUtilities.invokeLater(this)?
// And should updatePaddlePositions() be run() as a result?
}
And here's the paint method of the paddleOne and paddleTwo objects:
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
}
Feel free to comment on my design if anything pops out as "bad" to you. Lastly, what does Collections.synchronizedSet(new HashSet<Integer>()) mean/do?
Update #2: It seems like key bindings are the way to go (even though they take more code, in this case). What make key bindings better? Is it that they work separately from everything else (and don't need window focus like key listeners)?
Also, I understand that HashSet<Integer> is just a subclass of Set<Integer>, but what is the purpose of Collections.synchronizedSet(...)? I'm assuming it has to do with threads, but I don't know why it's needed in this program (if it is at all).
First off, use Swing KeyBindings Also I see no real need for multi-threadung unless you want your game multi-threaded.
To clarify the problem is you need to be able for 2 players to press different keys?
If so:
Solution:
Simply use booleans to flag whether or not a key is pressed down, you would than of course have to reset the flag when the key is released.
In your game logic you would check the states if the booleans and act appropriately.
See my below example (both paddles can move independently using W and S and UP and DOWN keys):
public class GameLogic {
public GameLogic() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Game Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create the gamepanel
final GamePanel gp = new GamePanel(600, 500);
//create panel to hold buttons to start pause and stop the game
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
final JButton startButton = new JButton("Start");
final JButton pauseButton = new JButton("Pause");
final JButton stopButton = new JButton("Stop");
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
//add listeners to buttons (most of the actions - excuse the pun - takes palce here :)
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//clear enitites currently in array
gp.clearEntities();
ArrayList<BufferedImage> ballEntityImages = new ArrayList<>();
ArrayList<Long> ballEntityTimings = new ArrayList<>();
ballEntityImages.add(createColouredImage("white", 50, 50, true));
ballEntityTimings.add(500l);
Entity ballEntity = new Entity(gp.getWidth() / 2, gp.getHeight() / 2, ballEntityImages, ballEntityTimings);
ballEntity.RIGHT = true;
//create images for entities
ArrayList<BufferedImage> advEntityImages = new ArrayList<>();
ArrayList<Long> advEntityTimings = new ArrayList<>();
advEntityImages.add(createColouredImage("orange", 10, 100, false));
advEntityTimings.add(500l);
advEntityImages.add(createColouredImage("blue", 10, 100, false));
advEntityTimings.add(500l);
//create entities
AdvancedSpritesEntity player1Entity = new AdvancedSpritesEntity(0, 100, advEntityImages, advEntityTimings);
ArrayList<BufferedImage> entityImages = new ArrayList<>();
ArrayList<Long> entityTimings = new ArrayList<>();
entityImages.add(createColouredImage("red", 10, 100, false));
entityTimings.add(500l);//as its the only image it doesnt really matter what time we put we could use 0l
//entityImages.add(createColouredImage("magenta", 100, 100));
//entityTimings.add(500l);
Entity player2Entity = new Entity(gp.getWidth() - 10, 200, entityImages, entityTimings);
gp.addEntity(player1Entity);
gp.addEntity(player2Entity);//just a standing still Entity for testing
gp.addEntity(ballEntity);//just a standing still Entity for testing
//create Keybingings for gamepanel
GameKeyBindings gameKeyBindings = new GameKeyBindings(gp, player1Entity, player2Entity);
GamePanel.running.set(true);
//start the game loop which will repaint the screen
runGameLoop(gp);
startButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
}
});
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
boolean b = GamePanel.paused.get();
GamePanel.paused.set(!b);//set it to the opposite of what it was i.e paused to unpaused and vice versa
if (pauseButton.getText().equals("Pause")) {
pauseButton.setText("Un-pause");
} else {
pauseButton.setText("Pause");
}
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
GamePanel.running.set(false);
GamePanel.paused.set(false);
/* if we want enitites to be cleared and a blank panel shown
gp.clearEntities();
gp.repaint();
*/
if (!pauseButton.getText().equals("Pause")) {
pauseButton.setText("Pause");
}
startButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
}
});
//add buttons to panel
buttonPanel.add(startButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
//add gamepanel to jframe and button panel
frame.add(gp);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//Simply used for testing (to simulate sprites) can create different colored images
public static BufferedImage createColouredImage(String color, int w, int h, boolean circular) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
switch (color.toLowerCase()) {
case "green":
g2.setColor(Color.GREEN);
break;
case "magenta":
g2.setColor(Color.MAGENTA);
break;
case "red":
g2.setColor(Color.RED);
break;
case "yellow":
g2.setColor(Color.YELLOW);
break;
case "blue":
g2.setColor(Color.BLUE);
break;
case "orange":
g2.setColor(Color.ORANGE);
break;
case "cyan":
g2.setColor(Color.CYAN);
break;
case "gray":
g2.setColor(Color.GRAY);
break;
default:
g2.setColor(Color.WHITE);
break;
}
if (!circular) {
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
} else {
g2.fillOval(0, 0, img.getWidth(), img.getHeight());
}
g2.dispose();
return img;
}
//Starts a new thread and runs the game loop in it.
private void runGameLoop(final GamePanel gp) {
Thread loop = new Thread(new Runnable() {
#Override
public void run() {
gp.gameLoop();
}
});
loop.start();
}
//Code starts here
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {//attempt to set look and feel to nimbus Java 7 and up
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GameLogic gameLogic = new GameLogic();
}
});
}
}
class GameKeyBindings {
public GameKeyBindings(JComponent gp, final Entity entity, final Entity entity2) {
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "W pressed");
gp.getActionMap().put("W pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "W released");
gp.getActionMap().put("W released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "S pressed");
gp.getActionMap().put("S pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "S released");
gp.getActionMap().put("S released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed");
gp.getActionMap().put("down pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down released");
gp.getActionMap().put("down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed");
gp.getActionMap().put("up pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up released");
gp.getActionMap().put("up released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = false;
}
});
}
}
class AdvancedSpritesEntity extends Entity {
public AdvancedSpritesEntity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(x, y, images, timings);
}
void setAnimation(ArrayList<BufferedImage> images, ArrayList<Long> timings) {
reset();//reset variables of animator class
setFrames(images, timings);//set new frames for animation
}
}
class Entity extends Animator {
private int speed = 5;
public boolean UP = false, DOWN = false, LEFT = false, RIGHT = false, visible;
private Rectangle2D.Double rect;
public Entity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(images, timings);
UP = false;
DOWN = false;
LEFT = false;
RIGHT = false;
visible = true;
rect = new Rectangle2D.Double(x, y, getCurrentImage().getWidth(), getCurrentImage().getHeight());
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public HashSet<String> getMask(Entity e) {
HashSet<String> mask = new HashSet<>();
int pixel, a;
BufferedImage bi = e.getCurrentImage();//gets the current image being shown
for (int i = 0; i < bi.getWidth(); i++) { // for every (x,y) component in the given box,
for (int j = 0; j < bi.getHeight(); j++) {
pixel = bi.getRGB(i, j); // get the RGB value of the pixel
a = (pixel >> 24) & 0xff;
if (a != 0) { // if the alpha is not 0, it must be something other than transparent
mask.add((e.getX() + i) + "," + (e.getY() - j)); // add the absolute x and absolute y coordinates to our set
}
}
}
return mask; //return our set
}
// Returns true if there is a collision between object a and object b
public boolean checkPerPixelCollision(Entity b) {
// This method detects to see if the images overlap at all. If they do, collision is possible
int ax1 = (int) getX();
int ay1 = (int) getY();
int ax2 = ax1 + (int) getWidth();
int ay2 = ay1 + (int) getHeight();
int bx1 = (int) b.getX();
int by1 = (int) b.getY();
int bx2 = bx1 + (int) b.getWidth();
int by2 = by1 + (int) b.getHeight();
if (by2 < ay1 || ay2 < by1 || bx2 < ax1 || ax2 < bx1) {
return false; // Collision is impossible.
} else { // Collision is possible.
// get the masks for both images
HashSet<String> maskPlayer1 = getMask(this);
HashSet<String> maskPlayer2 = getMask(b);
maskPlayer1.retainAll(maskPlayer2); // Check to see if any pixels in maskPlayer2 are the same as those in maskPlayer1
if (maskPlayer1.size() > 0) { // if so, than there exists at least one pixel that is the same in both images, thus
return true;
}
}
return false;
}
public void move() {
if (UP) {
rect.y -= speed;
}
if (DOWN) {
rect.y += speed;
}
if (LEFT) {
rect.x -= speed;
}
if (RIGHT) {
rect.x += speed;
}
}
#Override
public void update(long elapsedTime) {
super.update(elapsedTime);
getWidth();//set the rectangles height accordingly after image update
getHeight();//set rectangles height accordingle after update
}
public boolean intersects(Entity e) {
return rect.intersects(e.rect);
}
public double getX() {
return rect.x;
}
public double getY() {
return rect.y;
}
public double getWidth() {
if (getCurrentImage() == null) {//there might be no image (which is unwanted ofcourse but we must not get NPE so we check for null and return 0
return rect.width = 0;
}
return rect.width = getCurrentImage().getWidth();
}
public double getHeight() {
if (getCurrentImage() == null) {
return rect.height = 0;
}
return rect.height = getCurrentImage().getHeight();
}
}
class Animator {
private ArrayList<BufferedImage> frames;
private ArrayList<Long> timings;
private int currIndex;
private long animationTime;
private long totalAnimationDuration;
private AtomicBoolean done;//used to keep track if a single set of frames/ an animtion has finished its loop
public Animator(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
currIndex = 0;
animationTime = 0;
totalAnimationDuration = 0;
done = new AtomicBoolean(false);
this.frames = new ArrayList<>();
this.timings = new ArrayList<>();
setFrames(frames, timings);
}
public boolean isDone() {
return done.get();
}
public void reset() {
totalAnimationDuration = 0;
done.getAndSet(false);
}
public void update(long elapsedTime) {
if (frames.size() > 1) {
animationTime += elapsedTime;
if (animationTime >= totalAnimationDuration) {
animationTime = animationTime % totalAnimationDuration;
currIndex = 0;
done.getAndSet(true);
}
while (animationTime > timings.get(currIndex)) {
currIndex++;
}
}
}
public BufferedImage getCurrentImage() {
if (frames.isEmpty()) {
return null;
} else {
try {
return frames.get(currIndex);
} catch (Exception ex) {//images might have been altered so we reset the index and return first image of the new frames/animation
currIndex = 0;
return frames.get(currIndex);
}
}
}
public void setFrames(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
if (frames == null || timings == null) {//so that constructor super(null,null) cause this to throw NullPointerException
return;
}
this.frames = frames;
this.timings.clear();
for (long animTime : timings) {
totalAnimationDuration += animTime;
this.timings.add(totalAnimationDuration);
}
}
}
class GamePanel extends JPanel {
private final static RenderingHints textRenderHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
private final static RenderingHints imageRenderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
private final static RenderingHints colorRenderHints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
private final static RenderingHints interpolationRenderHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
private final static RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
public static AtomicBoolean running = new AtomicBoolean(false), paused = new AtomicBoolean(false);
private int width, height, frameCount = 0, fps = 0;
private ArrayList<Entity> entities = new ArrayList<>();
private final Random random = new Random();
public GamePanel(int w, int h) {
super(true);//make sure double buffering is enabled
setIgnoreRepaint(true);//mustnt repaint itself the gameloop will do that
width = w;
height = h;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public void addEntity(Entity e) {
entities.add(e);
}
void clearEntities() {
entities.clear();
}
//Only run this in another Thread!
public void gameLoop() {
//This value would probably be stored elsewhere.
final double GAME_HERTZ = 30.0;
//Calculate how many ns each frame should take for our target game hertz.
final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
//At the very most we will update the game this many times before a new render.
//If you're worried about visual hitches more than perfect timing, set this to 1.
final int MAX_UPDATES_BEFORE_RENDER = 5;
//We will need the last update time.
double lastUpdateTime = System.nanoTime();
//Store the last time we rendered.
double lastRenderTime = System.nanoTime();
//If we are able to get as high as this FPS, don't render again.
final double TARGET_FPS = 60;
final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;
//Simple way of finding FPS.
int lastSecondTime = (int) (lastUpdateTime / 1000000000);
//store the time we started this will be used for updating map and charcter animations
long currTime = System.currentTimeMillis();
while (running.get()) {
if (!paused.get()) {
double now = System.nanoTime();
long elapsedTime = System.currentTimeMillis() - currTime;
currTime += elapsedTime;
int updateCount = 0;
//Do as many game updates as we need to, potentially playing catchup.
while (now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER) {
updateGame(elapsedTime);//Update the entity movements and collision checks etc (all has to do with updating the games status i.e call move() on Enitites)
lastUpdateTime += TIME_BETWEEN_UPDATES;
updateCount++;
}
//If for some reason an update takes forever, we don't want to do an insane number of catchups.
//If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) {
lastUpdateTime = now - TIME_BETWEEN_UPDATES;
}
drawGame();//draw the game by invokeing repaint (which will call paintComponent) on this JPanel
lastRenderTime = now;
//Update the frames we got.
int thisSecond = (int) (lastUpdateTime / 1000000000);
if (thisSecond > lastSecondTime) {
//System.out.println("NEW SECOND " + thisSecond + " " + frameCount);
fps = frameCount;
frameCount = 0;
lastSecondTime = thisSecond;
}
//Yield until it has been at least the target time between renders. This saves the CPU from hogging.
while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
//allow the threading system to play threads that are waiting to run.
Thread.yield();
//This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
//You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
//FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
//On my OS(Windows 7 x64 intel i3) it does not allow for time to make enityt etc move thus all stands still
try {
Thread.sleep(1);
} catch (Exception e) {
}
now = System.nanoTime();
}
}
}
fps = 0;//no more running set fps to 0
}
private void drawGame() {
//Both revalidate and repaint are thread-safe — you need not invoke them from the event-dispatching thread. http://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
repaint();
}
private void updateGame(long elapsedTime) {
updateEntityMovements(elapsedTime);
checkForCollisions();
}
private void checkForCollisions() {
if (entities.get(0).intersects(entities.get(2)) || entities.get(1).intersects(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
} /*
//This is best used when images have transparent and non-transparent pixels (only detects pixel collisions of non-transparent pixels)
if (entities.get(0).checkPerPixelCollision(entities.get(2)) | entities.get(1).checkPerPixelCollision(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
}
*/
}
private void updateEntityMovements(long elapsedTime) {
for (Entity e : entities) {
e.update(elapsedTime);
e.move();
}
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
applyRenderHints(g2d);
drawBackground(g2d);
drawEntitiesToScreen(g2d);
drawFpsCounter(g2d);
frameCount++;
}
public static void applyRenderHints(Graphics2D g2d) {
g2d.setRenderingHints(textRenderHints);
g2d.setRenderingHints(imageRenderHints);
g2d.setRenderingHints(colorRenderHints);
g2d.setRenderingHints(interpolationRenderHints);
g2d.setRenderingHints(renderHints);
}
private void drawEntitiesToScreen(Graphics2D g2d) {
for (Entity e : entities) {
if (e.isVisible()) {
g2d.drawImage(e.getCurrentImage(), (int) e.getX(), (int) e.getY(), null);
}
}
}
private void drawFpsCounter(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.drawString("FPS: " + fps, 5, 10);
}
private void drawBackground(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
//thanks to trashgod for lovely testing background :) http://stackoverflow.com/questions/3256269/jtextfields-on-top-of-active-drawing-on-jpanel-threading-problems/3256941#3256941
g2d.setColor(Color.BLACK);
for (int i = 0; i < 128; i++) {
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));//random color
g2d.drawLine(getWidth() / 2, getHeight() / 2, random.nextInt(getWidth()), random.nextInt(getHeight()));
}
}
}
This may be a legitimate use case for the low-level access afforded to a KeyListener. See How to Write a Key Listener and KeyEventDemo; don't forget to requestFocusInWindow(). Also consider offering keyboard control for one player and mouse control for the other.
Addendum: #David Kroukamp has adduced an appealing counter-example using key bindings. For reference, the example cited here illustrates one approach to managing key preferences.
So I have this simple pong game but I'm trying to change it up a bit, the thing is I'm currently struggling with having to duplicate or create various balls in the game for it to work the way I want to. I'm uncertain if I should use an arraylist and if so how should I do it? any suggestions would really be appreciated.
public class ColorPong implements ApplicationListener {
private Rectangle field = new Rectangle();
private Ball ball = new Ball();
private float fieldTop, fieldBottom, fieldLeft, fieldRight;
#Override
public void create() {
field.set(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
fieldLeft = field.x;
fieldRight = field.x + field.width;
fieldBottom = field.y;
fieldTop = field.y + field.height;
ball.BallCreation();
reset();
}
#Override
public void resize(int width, int height) {
}
#Override
public void render() {
float dt = Gdx.graphics.getRawDeltaTime();
update(dt);
draw(dt);
}
private void draw(float dt) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
ball.DrawingBall(dt);
}
private void update(float dt) {
updateBall(dt);
}
private void updateBall(float dt) {
ball.Intergrate(dt);
ball.updateBounds();
//------------------
if(ball.Left() < fieldLeft){
ball.move(fieldLeft, ball.getY());
ball.Reflect(true, false);
}
if(ball.Right() > fieldRight){
ball.move(fieldRight - ball.getWidth(), ball.getY());
ball.Reflect(true, false);
}
if(ball.Bottom() < fieldBottom){
ball.move(ball.getX(), fieldBottom);
ball.Reflect(false, true);
}
if(ball.Top() > fieldTop){
ball.move(ball.getX(), fieldTop - ball.getHeight());
ball.Reflect(false, true);
}
}
public void reset(){
ball.move(field.x + (field.width - ball.getWidth()) / 2, (field.y + field.height) / 2);
Vector2 velocity = ball.getVelocity();
velocity.set(300, 150);
velocity.setAngle(360f - 45f);
ball.setVelocity(velocity);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
and here is the Ball class
private ShapeRenderer ballRenderer;
private Color ballColor = new Color();
public Ball() {
super(32, 32);
}
public void Reflect(boolean x, boolean y){
Vector2 velocity = getVelocity();
if(x) velocity.x *= -1;
if(y) velocity.y *= -1;
setVelocity(velocity);
}
public void BallCreation(){
ballRenderer = new ShapeRenderer();
}
public void DrawingBall(float dt){
ballRenderer.begin(ShapeType.Filled);
drawBall(dt);
ballColorSwap();
ballRenderer.end();
}
int THRESHOLD = 900; // 4 seconds
long lastChanged = 0; // timestamp
public void ballColorSwap(){
// maybe call it here?
if(System.currentTimeMillis() - lastChanged < THRESHOLD)
return;
int rnd = (int)(Math.random() * 4);
switch(rnd){
case 0: ballColor.set(Color.GREEN);break;
case 1: ballColor.set(Color.BLUE);break;
case 2: ballColor.set(Color.RED);break;
case 3: ballColor.set(Color.YELLOW);break;
}
lastChanged = System.currentTimeMillis();
}
private void drawBall(float dt) {
ballRenderer.circle(this.getX(), this.getY(), 20);
ballRenderer.setColor(ballColor);
}
}
In Java, whenever I want to keep track of an arbitrary number of objects I typically use an ArrayList; they are quite handy once you learn how to use them effectively.
Here's an example of how you might use an ArrayList with your update and updateBall methods:
//initialize in create()
ArrayList<Ball> balls;
private void update(float dt) {
//Pretty much saying 'For every ball in Balls, assign it to 'b' and do something with it
for(Ball b : balls) {
updateBall(b, dt);
}
}
private void updateBall(Ball b, float dt) {
b.Intergrate(dt);
b.updateBounds();
//------------------
if(b.Left() < fieldLeft){
b.move(fieldLeft, ball.getY());
b.Reflect(true, false);
}
if(b.Right() > fieldRight){
b.move(fieldRight - b.getWidth(), b.getY());
b.Reflect(true, false);
}
if(b.Bottom() < fieldBottom){
b.move(b.getX(), fieldBottom);
b.Reflect(false, true);
}
if(b.Top() > fieldTop){
b.move(b.getX(), fieldTop - b.getHeight());
b.Reflect(false, true);
}
}
And of course to draw the ball, just do the for(Ball.... thing again and call b.DrawingBall()
I'm new to Java graphics and threads, and I'm trying to make a game (specifically, Pong). The idea is that two people can play on the same keyboard (i.e. there are two paddles that are controlled through different keys). Currently, both players can't move their paddle at the same time.
Is there a solution to this? Are separate threads the answer?
If possible, I'd like the paddles to be able to move (at least seemingly) at the same time.
Update: It seems like using a Set<Integer> to store pressed keys is the best option. I've done that (and it works), but I'm wondering if any of this code is not on the Event Dispatching Thread (EDT) and if I need to use SwingUtilities.invokeLater();. Here's the necessary code:
private Set<Integer> keysDown = Collections.synchronizedSet(new HashSet<Integer>());
public void keyPressed(KeyEvent e)
{
keysDown.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e)
{
keysDown.remove(e.getKeyCode());
}
public void updatePaddlePositions()
{
if (keysDown.contains(KeyEvent.VK_W))
paddleOne.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_S))
paddleOne.move(PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_UP))
paddleTwo.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_DOWN))
paddleTwo.move(PADDLE_MOVE_INCREMENT);
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("You Interrupted the game!");
}
canvas.repaint();
}
Here's the paintComponent method of the canvas object:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paddleOne.paint(g);
paddleTwo.paint(g);
updatePaddlePositions(); // Does this need to be SwingUtilities.invokeLater(this)?
// And should updatePaddlePositions() be run() as a result?
}
And here's the paint method of the paddleOne and paddleTwo objects:
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
}
Feel free to comment on my design if anything pops out as "bad" to you. Lastly, what does Collections.synchronizedSet(new HashSet<Integer>()) mean/do?
Update #2: It seems like key bindings are the way to go (even though they take more code, in this case). What make key bindings better? Is it that they work separately from everything else (and don't need window focus like key listeners)?
Also, I understand that HashSet<Integer> is just a subclass of Set<Integer>, but what is the purpose of Collections.synchronizedSet(...)? I'm assuming it has to do with threads, but I don't know why it's needed in this program (if it is at all).
First off, use Swing KeyBindings Also I see no real need for multi-threadung unless you want your game multi-threaded.
To clarify the problem is you need to be able for 2 players to press different keys?
If so:
Solution:
Simply use booleans to flag whether or not a key is pressed down, you would than of course have to reset the flag when the key is released.
In your game logic you would check the states if the booleans and act appropriately.
See my below example (both paddles can move independently using W and S and UP and DOWN keys):
public class GameLogic {
public GameLogic() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Game Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create the gamepanel
final GamePanel gp = new GamePanel(600, 500);
//create panel to hold buttons to start pause and stop the game
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
final JButton startButton = new JButton("Start");
final JButton pauseButton = new JButton("Pause");
final JButton stopButton = new JButton("Stop");
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
//add listeners to buttons (most of the actions - excuse the pun - takes palce here :)
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//clear enitites currently in array
gp.clearEntities();
ArrayList<BufferedImage> ballEntityImages = new ArrayList<>();
ArrayList<Long> ballEntityTimings = new ArrayList<>();
ballEntityImages.add(createColouredImage("white", 50, 50, true));
ballEntityTimings.add(500l);
Entity ballEntity = new Entity(gp.getWidth() / 2, gp.getHeight() / 2, ballEntityImages, ballEntityTimings);
ballEntity.RIGHT = true;
//create images for entities
ArrayList<BufferedImage> advEntityImages = new ArrayList<>();
ArrayList<Long> advEntityTimings = new ArrayList<>();
advEntityImages.add(createColouredImage("orange", 10, 100, false));
advEntityTimings.add(500l);
advEntityImages.add(createColouredImage("blue", 10, 100, false));
advEntityTimings.add(500l);
//create entities
AdvancedSpritesEntity player1Entity = new AdvancedSpritesEntity(0, 100, advEntityImages, advEntityTimings);
ArrayList<BufferedImage> entityImages = new ArrayList<>();
ArrayList<Long> entityTimings = new ArrayList<>();
entityImages.add(createColouredImage("red", 10, 100, false));
entityTimings.add(500l);//as its the only image it doesnt really matter what time we put we could use 0l
//entityImages.add(createColouredImage("magenta", 100, 100));
//entityTimings.add(500l);
Entity player2Entity = new Entity(gp.getWidth() - 10, 200, entityImages, entityTimings);
gp.addEntity(player1Entity);
gp.addEntity(player2Entity);//just a standing still Entity for testing
gp.addEntity(ballEntity);//just a standing still Entity for testing
//create Keybingings for gamepanel
GameKeyBindings gameKeyBindings = new GameKeyBindings(gp, player1Entity, player2Entity);
GamePanel.running.set(true);
//start the game loop which will repaint the screen
runGameLoop(gp);
startButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
}
});
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
boolean b = GamePanel.paused.get();
GamePanel.paused.set(!b);//set it to the opposite of what it was i.e paused to unpaused and vice versa
if (pauseButton.getText().equals("Pause")) {
pauseButton.setText("Un-pause");
} else {
pauseButton.setText("Pause");
}
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
GamePanel.running.set(false);
GamePanel.paused.set(false);
/* if we want enitites to be cleared and a blank panel shown
gp.clearEntities();
gp.repaint();
*/
if (!pauseButton.getText().equals("Pause")) {
pauseButton.setText("Pause");
}
startButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
}
});
//add buttons to panel
buttonPanel.add(startButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
//add gamepanel to jframe and button panel
frame.add(gp);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//Simply used for testing (to simulate sprites) can create different colored images
public static BufferedImage createColouredImage(String color, int w, int h, boolean circular) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
switch (color.toLowerCase()) {
case "green":
g2.setColor(Color.GREEN);
break;
case "magenta":
g2.setColor(Color.MAGENTA);
break;
case "red":
g2.setColor(Color.RED);
break;
case "yellow":
g2.setColor(Color.YELLOW);
break;
case "blue":
g2.setColor(Color.BLUE);
break;
case "orange":
g2.setColor(Color.ORANGE);
break;
case "cyan":
g2.setColor(Color.CYAN);
break;
case "gray":
g2.setColor(Color.GRAY);
break;
default:
g2.setColor(Color.WHITE);
break;
}
if (!circular) {
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
} else {
g2.fillOval(0, 0, img.getWidth(), img.getHeight());
}
g2.dispose();
return img;
}
//Starts a new thread and runs the game loop in it.
private void runGameLoop(final GamePanel gp) {
Thread loop = new Thread(new Runnable() {
#Override
public void run() {
gp.gameLoop();
}
});
loop.start();
}
//Code starts here
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {//attempt to set look and feel to nimbus Java 7 and up
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GameLogic gameLogic = new GameLogic();
}
});
}
}
class GameKeyBindings {
public GameKeyBindings(JComponent gp, final Entity entity, final Entity entity2) {
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "W pressed");
gp.getActionMap().put("W pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "W released");
gp.getActionMap().put("W released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "S pressed");
gp.getActionMap().put("S pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "S released");
gp.getActionMap().put("S released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed");
gp.getActionMap().put("down pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down released");
gp.getActionMap().put("down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed");
gp.getActionMap().put("up pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up released");
gp.getActionMap().put("up released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = false;
}
});
}
}
class AdvancedSpritesEntity extends Entity {
public AdvancedSpritesEntity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(x, y, images, timings);
}
void setAnimation(ArrayList<BufferedImage> images, ArrayList<Long> timings) {
reset();//reset variables of animator class
setFrames(images, timings);//set new frames for animation
}
}
class Entity extends Animator {
private int speed = 5;
public boolean UP = false, DOWN = false, LEFT = false, RIGHT = false, visible;
private Rectangle2D.Double rect;
public Entity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(images, timings);
UP = false;
DOWN = false;
LEFT = false;
RIGHT = false;
visible = true;
rect = new Rectangle2D.Double(x, y, getCurrentImage().getWidth(), getCurrentImage().getHeight());
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public HashSet<String> getMask(Entity e) {
HashSet<String> mask = new HashSet<>();
int pixel, a;
BufferedImage bi = e.getCurrentImage();//gets the current image being shown
for (int i = 0; i < bi.getWidth(); i++) { // for every (x,y) component in the given box,
for (int j = 0; j < bi.getHeight(); j++) {
pixel = bi.getRGB(i, j); // get the RGB value of the pixel
a = (pixel >> 24) & 0xff;
if (a != 0) { // if the alpha is not 0, it must be something other than transparent
mask.add((e.getX() + i) + "," + (e.getY() - j)); // add the absolute x and absolute y coordinates to our set
}
}
}
return mask; //return our set
}
// Returns true if there is a collision between object a and object b
public boolean checkPerPixelCollision(Entity b) {
// This method detects to see if the images overlap at all. If they do, collision is possible
int ax1 = (int) getX();
int ay1 = (int) getY();
int ax2 = ax1 + (int) getWidth();
int ay2 = ay1 + (int) getHeight();
int bx1 = (int) b.getX();
int by1 = (int) b.getY();
int bx2 = bx1 + (int) b.getWidth();
int by2 = by1 + (int) b.getHeight();
if (by2 < ay1 || ay2 < by1 || bx2 < ax1 || ax2 < bx1) {
return false; // Collision is impossible.
} else { // Collision is possible.
// get the masks for both images
HashSet<String> maskPlayer1 = getMask(this);
HashSet<String> maskPlayer2 = getMask(b);
maskPlayer1.retainAll(maskPlayer2); // Check to see if any pixels in maskPlayer2 are the same as those in maskPlayer1
if (maskPlayer1.size() > 0) { // if so, than there exists at least one pixel that is the same in both images, thus
return true;
}
}
return false;
}
public void move() {
if (UP) {
rect.y -= speed;
}
if (DOWN) {
rect.y += speed;
}
if (LEFT) {
rect.x -= speed;
}
if (RIGHT) {
rect.x += speed;
}
}
#Override
public void update(long elapsedTime) {
super.update(elapsedTime);
getWidth();//set the rectangles height accordingly after image update
getHeight();//set rectangles height accordingle after update
}
public boolean intersects(Entity e) {
return rect.intersects(e.rect);
}
public double getX() {
return rect.x;
}
public double getY() {
return rect.y;
}
public double getWidth() {
if (getCurrentImage() == null) {//there might be no image (which is unwanted ofcourse but we must not get NPE so we check for null and return 0
return rect.width = 0;
}
return rect.width = getCurrentImage().getWidth();
}
public double getHeight() {
if (getCurrentImage() == null) {
return rect.height = 0;
}
return rect.height = getCurrentImage().getHeight();
}
}
class Animator {
private ArrayList<BufferedImage> frames;
private ArrayList<Long> timings;
private int currIndex;
private long animationTime;
private long totalAnimationDuration;
private AtomicBoolean done;//used to keep track if a single set of frames/ an animtion has finished its loop
public Animator(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
currIndex = 0;
animationTime = 0;
totalAnimationDuration = 0;
done = new AtomicBoolean(false);
this.frames = new ArrayList<>();
this.timings = new ArrayList<>();
setFrames(frames, timings);
}
public boolean isDone() {
return done.get();
}
public void reset() {
totalAnimationDuration = 0;
done.getAndSet(false);
}
public void update(long elapsedTime) {
if (frames.size() > 1) {
animationTime += elapsedTime;
if (animationTime >= totalAnimationDuration) {
animationTime = animationTime % totalAnimationDuration;
currIndex = 0;
done.getAndSet(true);
}
while (animationTime > timings.get(currIndex)) {
currIndex++;
}
}
}
public BufferedImage getCurrentImage() {
if (frames.isEmpty()) {
return null;
} else {
try {
return frames.get(currIndex);
} catch (Exception ex) {//images might have been altered so we reset the index and return first image of the new frames/animation
currIndex = 0;
return frames.get(currIndex);
}
}
}
public void setFrames(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
if (frames == null || timings == null) {//so that constructor super(null,null) cause this to throw NullPointerException
return;
}
this.frames = frames;
this.timings.clear();
for (long animTime : timings) {
totalAnimationDuration += animTime;
this.timings.add(totalAnimationDuration);
}
}
}
class GamePanel extends JPanel {
private final static RenderingHints textRenderHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
private final static RenderingHints imageRenderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
private final static RenderingHints colorRenderHints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
private final static RenderingHints interpolationRenderHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
private final static RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
public static AtomicBoolean running = new AtomicBoolean(false), paused = new AtomicBoolean(false);
private int width, height, frameCount = 0, fps = 0;
private ArrayList<Entity> entities = new ArrayList<>();
private final Random random = new Random();
public GamePanel(int w, int h) {
super(true);//make sure double buffering is enabled
setIgnoreRepaint(true);//mustnt repaint itself the gameloop will do that
width = w;
height = h;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public void addEntity(Entity e) {
entities.add(e);
}
void clearEntities() {
entities.clear();
}
//Only run this in another Thread!
public void gameLoop() {
//This value would probably be stored elsewhere.
final double GAME_HERTZ = 30.0;
//Calculate how many ns each frame should take for our target game hertz.
final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
//At the very most we will update the game this many times before a new render.
//If you're worried about visual hitches more than perfect timing, set this to 1.
final int MAX_UPDATES_BEFORE_RENDER = 5;
//We will need the last update time.
double lastUpdateTime = System.nanoTime();
//Store the last time we rendered.
double lastRenderTime = System.nanoTime();
//If we are able to get as high as this FPS, don't render again.
final double TARGET_FPS = 60;
final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;
//Simple way of finding FPS.
int lastSecondTime = (int) (lastUpdateTime / 1000000000);
//store the time we started this will be used for updating map and charcter animations
long currTime = System.currentTimeMillis();
while (running.get()) {
if (!paused.get()) {
double now = System.nanoTime();
long elapsedTime = System.currentTimeMillis() - currTime;
currTime += elapsedTime;
int updateCount = 0;
//Do as many game updates as we need to, potentially playing catchup.
while (now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER) {
updateGame(elapsedTime);//Update the entity movements and collision checks etc (all has to do with updating the games status i.e call move() on Enitites)
lastUpdateTime += TIME_BETWEEN_UPDATES;
updateCount++;
}
//If for some reason an update takes forever, we don't want to do an insane number of catchups.
//If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) {
lastUpdateTime = now - TIME_BETWEEN_UPDATES;
}
drawGame();//draw the game by invokeing repaint (which will call paintComponent) on this JPanel
lastRenderTime = now;
//Update the frames we got.
int thisSecond = (int) (lastUpdateTime / 1000000000);
if (thisSecond > lastSecondTime) {
//System.out.println("NEW SECOND " + thisSecond + " " + frameCount);
fps = frameCount;
frameCount = 0;
lastSecondTime = thisSecond;
}
//Yield until it has been at least the target time between renders. This saves the CPU from hogging.
while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
//allow the threading system to play threads that are waiting to run.
Thread.yield();
//This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
//You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
//FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
//On my OS(Windows 7 x64 intel i3) it does not allow for time to make enityt etc move thus all stands still
try {
Thread.sleep(1);
} catch (Exception e) {
}
now = System.nanoTime();
}
}
}
fps = 0;//no more running set fps to 0
}
private void drawGame() {
//Both revalidate and repaint are thread-safe — you need not invoke them from the event-dispatching thread. http://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
repaint();
}
private void updateGame(long elapsedTime) {
updateEntityMovements(elapsedTime);
checkForCollisions();
}
private void checkForCollisions() {
if (entities.get(0).intersects(entities.get(2)) || entities.get(1).intersects(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
} /*
//This is best used when images have transparent and non-transparent pixels (only detects pixel collisions of non-transparent pixels)
if (entities.get(0).checkPerPixelCollision(entities.get(2)) | entities.get(1).checkPerPixelCollision(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
}
*/
}
private void updateEntityMovements(long elapsedTime) {
for (Entity e : entities) {
e.update(elapsedTime);
e.move();
}
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
applyRenderHints(g2d);
drawBackground(g2d);
drawEntitiesToScreen(g2d);
drawFpsCounter(g2d);
frameCount++;
}
public static void applyRenderHints(Graphics2D g2d) {
g2d.setRenderingHints(textRenderHints);
g2d.setRenderingHints(imageRenderHints);
g2d.setRenderingHints(colorRenderHints);
g2d.setRenderingHints(interpolationRenderHints);
g2d.setRenderingHints(renderHints);
}
private void drawEntitiesToScreen(Graphics2D g2d) {
for (Entity e : entities) {
if (e.isVisible()) {
g2d.drawImage(e.getCurrentImage(), (int) e.getX(), (int) e.getY(), null);
}
}
}
private void drawFpsCounter(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.drawString("FPS: " + fps, 5, 10);
}
private void drawBackground(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
//thanks to trashgod for lovely testing background :) http://stackoverflow.com/questions/3256269/jtextfields-on-top-of-active-drawing-on-jpanel-threading-problems/3256941#3256941
g2d.setColor(Color.BLACK);
for (int i = 0; i < 128; i++) {
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));//random color
g2d.drawLine(getWidth() / 2, getHeight() / 2, random.nextInt(getWidth()), random.nextInt(getHeight()));
}
}
}
This may be a legitimate use case for the low-level access afforded to a KeyListener. See How to Write a Key Listener and KeyEventDemo; don't forget to requestFocusInWindow(). Also consider offering keyboard control for one player and mouse control for the other.
Addendum: #David Kroukamp has adduced an appealing counter-example using key bindings. For reference, the example cited here illustrates one approach to managing key preferences.