Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
1
Indexable
Never
Sure! Here's an example of a basic gaming application in Java:

```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel {

    private int x; // x-coordinate of the player
    private int y; // y-coordinate of the player

    public Game() {
        this.setPreferredSize(new Dimension(500, 500));
        this.setFocusable(true);
        this.requestFocus();
        this.addKeyListener(new MyKeyListener());
        x = 250;
        y = 250;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillRect(x, y, 50, 50); // draw the player as a red rectangle
    }

    public void update() {
        // update the player's position, game logic, etc.
    }

    private class MyKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_UP) {
                y -= 10; // move the player up
            } else if (key == KeyEvent.VK_DOWN) {
                y += 10; // move the player down
            } else if (key == KeyEvent.VK_LEFT) {
                x -= 10; // move the player left
            } else if (key == KeyEvent.VK_RIGHT) {
                x += 10; // move the player right
            }
            repaint(); // repaint the panel to update the player's position
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.getContentPane().add(new Game());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
```

This code creates a simple game where you can control a player using the arrow keys. The player is represented by a red rectangle that can be moved up, down, left, and right using the arrow keys. The game panel is displayed in a JFrame window.

You can add your own game logic and additional features to this basic framework.