Copy code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BottleFlipGame extends JFrame {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int BOTTLE_WIDTH = 50;
private static final int BOTTLE_HEIGHT = 100;
private Timer timer;
private int bottleX;
private int bottleY;
private int bottleSpeedY;
public BottleFlipGame() {
setTitle("Bottle Flip Game");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
bottleX = WIDTH / 2 - BOTTLE_WIDTH / 2;
bottleY = HEIGHT - BOTTLE_HEIGHT - 30;
bottleSpeedY = 0;
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
setFocusable(true);
}
private void formKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_SPACE && bottleSpeedY == 0) {
bottleSpeedY = -5; // Jump when space is pressed
}
}
private void update() {
// Update bottle position
bottleY += bottleSpeedY;
bottleSpeedY += 1; // Gravity effect
// Check if the bottle hits the ground
if (bottleY > HEIGHT - BOTTLE_HEIGHT - 30) {
bottleY = HEIGHT - BOTTLE_HEIGHT - 30;
bottleSpeedY = 0;
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
// Draw the bottle
g.setColor(Color.BLUE);
g.fillRect(bottleX, bottleY, BOTTLE_WIDTH, BOTTLE_HEIGHT);
// Draw ground
g.setColor(Color.GREEN);
g.fillRect(0, HEIGHT - 30, WIDTH, 30);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
BottleFlipGame bottleFlipGame = new BottleFlipGame();
bottleFlipGame.setVisible(true);
bottleFlipGame.timer.start();
}
});
}
}
Comments