Tuesday, July 22, 2025

java control for game

# Java Swing Game with File Loading and Input Controls

I'll create a simple Java Swing game that loads data from a file and responds to keyboard and mouse input. This example demonstrates file handling, Swing components, and input event listeners.

## Complete Game Example

```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class SwingGame extends JFrame {
    private GamePanel gamePanel;
    private Player player;
    private List<Enemy> enemies = new ArrayList<>();
    private boolean[] keysPressed = new boolean[256];

    public SwingGame() {
        setTitle("File-Based Swing Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        
        gamePanel = new GamePanel();
        add(gamePanel);
        
        // Load game data from file
        try {
            loadGameData("game_data.txt");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "Error loading game data: " + e.getMessage(),
                                        "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        
        // Keyboard input
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                keysPressed[e.getKeyCode()] = true;
            }
            
            @Override
            public void keyReleased(KeyEvent e) {
                keysPressed[e.getKeyCode()] = false;
            }
        });
        
        // Mouse input
        gamePanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                player.moveTo(e.getX(), e.getY());
            }
        });
        
        // Game loop
        Timer gameTimer = new Timer(16, e -> {
            updateGame();
            gamePanel.repaint();
        });
        gameTimer.start();
    }
    
    private void loadGameData(String filename) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("PLAYER:")) {
                    String[] parts = line.split(":");
                    player = new Player(parts[1].trim(), 400, 300);
                } else if (line.startsWith("ENEMY:")) {
                    String[] parts = line.split(":");
                    String[] coords = parts[2].split(",");
                    enemies.add(new Enemy(parts[1].trim(), 
                                        Integer.parseInt(coords[0].trim()),
                                        Integer.parseInt(coords[1].trim())));
                }
            }
        }
        
        if (player == null) {
            player = new Player("Default Player", 400, 300);
        }
    }
    
    private void updateGame() {
        // Handle keyboard input
        if (keysPressed[KeyEvent.VK_W] || keysPressed[KeyEvent.VK_UP]) {
            player.move(0, -5);
        }
        if (keysPressed[KeyEvent.VK_S] || keysPressed[KeyEvent.VK_DOWN]) {
            player.move(0, 5);
        }
        if (keysPressed[KeyEvent.VK_A] || keysPressed[KeyEvent.VK_LEFT]) {
            player.move(-5, 0);
        }
        if (keysPressed[KeyEvent.VK_D] || keysPressed[KeyEvent.VK_RIGHT]) {
            player.move(5, 0);
        }
        
        // Simple enemy AI - move toward player
        for (Enemy enemy : enemies) {
            int dx = Integer.compare(player.x, enemy.x);
            int dy = Integer.compare(player.y, enemy.y);
            enemy.move(dx * 2, dy * 2);
        }
    }
    
    private class GamePanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            // Draw background
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, getWidth(), getHeight());
            
            // Draw player
            player.draw(g);
            
            // Draw enemies
            for (Enemy enemy : enemies) {
                enemy.draw(g);
            }
            
            // Draw instructions
            g.setColor(Color.WHITE);
            g.drawString("Use WASD/Arrow keys to move or click to teleport", 10, 20);
            g.drawString("Player: " + player.name, 10, 40);
        }
    }
    
    private class Player {
        String name;
        int x, y;
        Color color = Color.GREEN;
        
        Player(String name, int x, int y) {
            this.name = name;
            this.x = x;
            this.y = y;
        }
        
        void move(int dx, int dy) {
            x += dx;
            y += dy;
            // Simple bounds checking
            x = Math.max(20, Math.min(getWidth() - 20, x));
            y = Math.max(20, Math.min(getHeight() - 20, y));
        }
        
        void moveTo(int newX, int newY) {
            x = newX;
            y = newY;
        }
        
        void draw(Graphics g) {
            g.setColor(color);
            g.fillOval(x - 15, y - 15, 30, 30);
            g.setColor(Color.WHITE);
            g.drawString(name, x - 15, y - 20);
        }
    }
    
    private class Enemy {
        String name;
        int x, y;
        Color color = Color.RED;
        
        Enemy(String name, int x, int y) {
            this.name = name;
            this.x = x;
            this.y = y;
        }
        
        void move(int dx, int dy) {
            x += dx;
            y += dy;
        }
        
        void draw(Graphics g) {
            g.setColor(color);
            g.fillRect(x - 15, y - 15, 30, 30);
            g.setColor(Color.WHITE);
            g.drawString(name, x - 15, y - 20);
        }
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SwingGame game = new SwingGame();
            game.setVisible(true);
        });
    }
}
```

## Sample game_data.txt File

```
PLAYER:Hero
ENEMY:Goblin:100,100
ENEMY:Orc:700,100
ENEMY:Troll:100,500
ENEMY:Dragon:700,500
```

## Features of This Implementation

1. **File Loading**: Loads player and enemy data from a text file
2. **Keyboard Controls**: WASD or arrow keys to move the player
3. **Mouse Controls**: Click to teleport the player
4. **Game Loop**: Smooth animation using a Swing Timer
5. **Simple AI**: Enemies chase the player

## How to Run

1. Create `SwingGame.java` with the code above
2. Create `game_data.txt` with the sample content
3. Compile and run:
   ```
   javac SwingGame.java
   java SwingGame
   ```

## Key Concepts Explained

1. **Swing Components**: Using JFrame and JPanel for the game window
2. **Event Listeners**:
   - KeyListener for keyboard input
   - MouseListener for mouse clicks
3. **Game Loop**: Using javax.swing.Timer for consistent updates
4. **File Handling**: Reading game data with BufferedReader
5. **Painting**: Custom drawing in paintComponent() method

## Possible Enhancements

1. Add collision detection between player and enemies
2. Implement scoring system
3. Add game states (menu, playing, game over)
4. Support more complex file formats (JSON, XML)
5. Add sound effects and more visual feedback

Would you like me to explain any specific part in more detail or add any particular features to this example?

No comments: