写一个马里奥小游戏用java语言
时间: 2023-07-20 17:17:27 浏览: 118
简单Java开发的超级马里奥小游戏.zip
好的,以下是一个简单的马里奥小游戏的 Java 代码,实现了基本的移动和跳跃功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MarioGame extends JFrame implements ActionListener {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int GROUND_Y = 500;
private static final int MARIO_WIDTH = 50;
private static final int MARIO_HEIGHT = 50;
private static final int MARIO_JUMP_HEIGHT = 100;
private static final int MARIO_JUMP_SPEED = 10;
private Timer timer;
private boolean isJumping;
private int jumpCount;
private int marioX;
private int marioY;
private int marioSpeedX;
private int marioSpeedY;
public MarioGame() {
setTitle("Mario Game");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
isJumping = false;
jumpCount = 0;
marioX = 0;
marioY = GROUND_Y - MARIO_HEIGHT;
marioSpeedX = 0;
marioSpeedY = 0;
timer = new Timer(20, this);
timer.start();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
marioSpeedX = -5;
} else if (keyCode == KeyEvent.VK_RIGHT) {
marioSpeedX = 5;
} else if (keyCode == KeyEvent.VK_SPACE && !isJumping) {
isJumping = true;
jumpCount = 0;
marioSpeedY = -MARIO_JUMP_SPEED;
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT) {
marioSpeedX = 0;
}
}
});
setFocusable(true);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
updateMarioPosition();
repaint();
}
private void updateMarioPosition() {
marioX += marioSpeedX;
if (isJumping) {
marioY += marioSpeedY;
jumpCount++;
if (jumpCount == MARIO_JUMP_HEIGHT / MARIO_JUMP_SPEED) {
marioSpeedY = MARIO_JUMP_SPEED;
}
if (marioY >= GROUND_Y - MARIO_HEIGHT) {
marioY = GROUND_Y - MARIO_HEIGHT;
isJumping = false;
}
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.GREEN);
g.fillRect(0, GROUND_Y, WIDTH, HEIGHT - GROUND_Y);
g.setColor(Color.RED);
g.fillRect(marioX, marioY, MARIO_WIDTH, MARIO_HEIGHT);
}
public static void main(String[] args) {
new MarioGame();
}
}
```
这个马里奥小游戏实现了基本的移动和跳跃功能。玩家可以用左右箭头键控制马里奥的移动,用空格键控制马里奥的跳跃。游戏中有一个绿色的地面和一个红色的马里奥。玩家可以在地面上移动和跳跃,如果跳得太高会落回地面。
阅读全文