使用Python,结合pygame库,设计一个十分简单的小游戏
时间: 2024-01-25 07:02:15 浏览: 75
好的,我可以为您提供一个简单的小游戏:打地鼠游戏。
步骤如下:
1. 安装pygame库,可以使用pip命令:`pip install pygame`
2. 创建一个窗口,并设置窗口大小:
```python
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Whack-a-Mole")
```
3. 加载游戏所需的图片资源:
```python
background = pygame.image.load("background.png")
mole = pygame.image.load("mole.png")
hammer = pygame.image.load("hammer.png")
```
4. 创建一个计时器,控制地鼠出现的频率,并且创建一个列表,保存地鼠出现的位置:
```python
import random
spawn_time = pygame.time.get_ticks() + 1000 # 1000毫秒后出现第一只地鼠
mole_positions = [] # 地鼠出现的位置列表
def add_mole():
x = random.randint(0, 400)
y = random.randint(0, 400)
mole_positions.append((x, y))
while True:
now = pygame.time.get_ticks()
if now >= spawn_time:
add_mole()
spawn_time = now + random.randint(500, 2000) # 下一只地鼠出现的时间
# 绘制地鼠
for pos in mole_positions:
screen.blit(mole, pos)
```
5. 监听鼠标事件,当鼠标点击地鼠时,地鼠消失,并且加分:
```python
score = 0 # 分数
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for mole_pos in mole_positions:
if mole_pos[0] <= pos[0] <= mole_pos[0] + 50 and mole_pos[1] <= pos[1] <= mole_pos[1] + 50:
mole_positions.remove(mole_pos)
score += 1
# 绘制锤子
pos = pygame.mouse.get_pos()
screen.blit(hammer, (pos[0] - 25, pos[1] - 25))
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render("Score: {}".format(score), True, (255, 255, 255))
screen.blit(text, (10, 10))
pygame.display.update()
```
6. 最后运行游戏,完整代码如下:
```python
import pygame
import random
import sys
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Whack-a-Mole")
background = pygame.image.load("background.png")
mole = pygame.image.load("mole.png")
hammer = pygame.image.load("hammer.png")
spawn_time = pygame.time.get_ticks() + 1000
mole_positions = []
score = 0
def add_mole():
x = random.randint(0, 400)
y = random.randint(0, 400)
mole_positions.append((x, y))
while True:
now = pygame.time.get_ticks()
if now >= spawn_time:
add_mole()
spawn_time = now + random.randint(500, 2000)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for mole_pos in mole_positions:
if mole_pos[0] <= pos[0] <= mole_pos[0] + 50 and mole_pos[1] <= pos[1] <= mole_pos[1] + 50:
mole_positions.remove(mole_pos)
score += 1
screen.blit(background, (0, 0))
for pos in mole_positions:
screen.blit(mole, pos)
pos = pygame.mouse.get_pos()
screen.blit(hammer, (pos[0] - 25, pos[1] - 25))
font = pygame.font.Font(None, 36)
text = font.render("Score: {}".format(score), True, (255, 255, 255))
screen.blit(text, (10, 10))
pygame.display.update()
```
希望我提供的代码可以帮助到您。
阅读全文