- Python (使用pygame库)cy2.cn
首先,你需要安装pygame库:
bash
pip install pygame
然后,一个简单的Pygame游戏可能如下(示例:移动一个矩形):
python
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption(“简单游戏”)
rect = pygame.Rect(50, 50, 50, 50)
rect_speed = [2, 2]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255)) # 背景色为白色
pygame.draw.rect(screen, (0, 0, 255), rect) # 绘制蓝色矩形
rect.move_ip(rect_speed) # 移动矩形
if rect.left < 0 or rect.right > 800:
rect_speed[0] = -rect_speed[0] # 碰到左右边界则反弹
if rect.top < 0 or rect.bottom > 600:
rect_speed[1] = -rect_speed[1] # 碰到上下边界则反弹
pygame.display.flip()
pygame.time.Clock().tick(60) # 控制帧率
- JavaScript (使用HTML Canvas)
一个简单的HTML Canvas游戏可能如下(示例:移动一个圆形):
html
java
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleGame extends JFrame implements ActionListener {
private int x = 50, y = 50;
private int dx = 2, dy = 2;
public SimpleGame() {
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel ball = new JLabel("O");
ball.setBounds(x, y, 20, 20);
add(ball);
Timer timer = new Timer(50, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
由于篇幅限制,我无法为所有编程语言都提供一个完整的小程序游戏代码,但我可以为你提供几种流行编程语言(如Python、JavaScript、Java)的简单游戏示例:
- Python (使用pygame库)
首先,你需要安装pygame库:
bash
pip install pygame
然后,一个简单的Pygame游戏可能如下(示例:移动一个矩形):
python
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption(“简单游戏”)
rect = pygame.Rect(50, 50, 50, 50)
rect_speed = [2, 2]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255)) # 背景色为白色
pygame.draw.rect(screen, (0, 0, 255), rect) # 绘制蓝色矩形
rect.move_ip(rect_speed) # 移动矩形
if rect.left < 0 or rect.right > 800:
rect_speed[0] = -rect_speed[0] # 碰到左右边界则反弹
if rect.top < 0 or rect.bottom > 600:
rect_speed[1] = -rect_speed[1] # 碰到上下边界则反弹
pygame.display.flip()
pygame.time.Clock().tick(60) # 控制帧率
- JavaScript (使用HTML Canvas)
一个简单的HTML Canvas游戏可能如下(示例:移动一个圆形):
html
java
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleGame extends JFrame implements ActionListener {
private int x = 50, y = 50;
private int dx = 2, dy = 2;
public SimpleGame() {
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel ball = new JLabel("O");
ball.setBounds(x, y, 20, 20);
add(ball);
Timer timer = new Timer(50, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;