quhluh icon

Jump

quhluh | 12/09/23 05:23:09 AM UTC | 0 ⭐ | 717 👁️ | Never ⏰ | []
Java |

2.82 KB

|

None

|

0 👍

/

0 👎

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
public class JumpingGame extends JFrame {
 
    private static final int WIDTH = 400;
    private static final int HEIGHT = 400;
    private static final int GROUND_HEIGHT = 300;
 
    private int characterY = GROUND_HEIGHT;
 
    public JumpingGame() {
        setTitle("Jumping Game");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        JumpingPanel jumpingPanel = new JumpingPanel();
        add(jumpingPanel);
 
        addKeyListener(new JumpingKeyListener());
 
        Timer timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jumpingPanel.update();
            }
        });
        timer.start();
    }
 
    private class JumpingPanel extends JPanel {
 
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLUE);
            g.fillRect(50, characterY, 30, 30);
        }
 
        public void update() {
            if (characterY < GROUND_HEIGHT) {
                characterY += 2; // Simulating gravity
                repaint();
            }
        }
    }
 
    private class JumpingKeyListener implements KeyListener {
 
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_SPACE && characterY == GROUND_HEIGHT) {
                jump();
            }
        }
 
        @Override
        public void keyTyped(KeyEvent e) {
            // Not used
        }
 
        @Override
        public void keyReleased(KeyEvent e) {
            // Not used
        }
 
        private void jump() {
            // Simulate jumping by moving the character upwards
            characterY -= 50;
        }
    }
 
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JumpingGame().setVisible(true);
            }
        });
    }
}
This code creates a simple jumping game where the character jumps when you press the space bar. The JumpingGame class extends JFrame and contains a JumpingPanel class that extends JPanel. The character is represented by a blue rectangle, and jumping is simulated by changing the character's vertical position. The JumpingKeyListener class listens for the space bar key press and triggers the jump.
 
Note: This is a basic example for educational purposes. In a real game, you would likely use a game engine or a more sophisticated graphics library for better performance and flexibility.
 
 
 
 
 
 

Comments