import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Game extends JPanel implements Runnable, KeyListener {
private boolean running = true;
private Player player;
private Enemy enemy;
private Thread gameThread;
public Game() {
player = new Player();
enemy = new Enemy();
this.addKeyListener(this);
this.setFocusable(true);
this.setFocusTraversalKeysEnabled(false);
gameThread = new Thread(this);
gameThread.start();
}
@Override
public void run() {
while (running) {
update();
repaint();
try {
Thread.sleep(16); // roughly 60 FPS
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update() {
player.update();
enemy.update();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
player.render(g);
enemy.render(g);
}
@Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
@Override
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Game");
Game game = new Game();
frame.add(game);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Player {
private int x, y, velocityY;
private boolean onGround = true, movingLeft = false, movingRight = false, jumping = false;
private final int speed = 5, jumpStrength = 10, gravity = 1;
public void update() {
if (movingLeft) x -= speed;
if (movingRight) x += speed;
if (jumping && onGround) {
velocityY = -jumpStrength;
onGround = false;
}
y += velocityY;
if (y >= 500) { // Assuming ground level is at y = 500
y = 500;
onGround = true;
velocityY = 0;
} else {
velocityY += gravity;
}
}
public void render(Graphics g) {
g.fillRect(x, y, 50, 50); // Draw player as a rectangle
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) movingLeft = true;
if (key == KeyEvent.VK_RIGHT) movingRight = true;
if (key == KeyEvent.VK_SPACE) jumping = true;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) movingLeft = false;
if (key == KeyEvent.VK_RIGHT) movingRight = false;
if (key == KeyEvent.VK_SPACE) jumping = false;
}
}
class Enemy {
private int x, y;
public void update() {
// Enemy AI logic
}
public void render(Graphics g) {
g.fillRect(x, y, 50, 50); // Draw enemy as a rectangle
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter