python打地鼠游戏代码
时间: 2023-10-13 07:21:27 浏览: 104
打地鼠游戏代码
以下是一个简单的 Python 打地鼠游戏代码:
```python
import random
import time
# 设置画布大小
WIDTH = 800
HEIGHT = 600
# 设置地鼠出现的范围
MOLE_X_MIN, MOLE_X_MAX = 50, 750
MOLE_Y_MIN, MOLE_Y_MAX = 50, 550
# 设置游戏时间
GAME_TIME = 30
# 初始化游戏
game_over = False
score = 0
start_time = time.time()
# 创建地鼠
class Mole:
def __init__(self):
self.x = random.randint(MOLE_X_MIN, MOLE_X_MAX)
self.y = random.randint(MOLE_Y_MIN, MOLE_Y_MAX)
self.show_time = time.time()
self.hide_time = self.show_time + random.randint(1, 3)
self.visible = True
def show(self):
self.visible = True
self.show_time = time.time()
self.hide_time = self.show_time + random.randint(1, 3)
def hide(self):
self.visible = False
self.show_time = time.time()
def update(self):
if time.time() >= self.hide_time:
self.hide()
elif not self.visible and time.time() >= self.show_time:
self.show()
# 创建地鼠列表
moles = [Mole() for i in range(5)]
# 开始游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEBUTTONDOWN:
for mole in moles:
if mole.visible and mole.x - 50 <= event.pos[0] <= mole.x + 50 and mole.y - 50 <= event.pos[1] <= mole.y + 50:
score += 1
mole.hide()
# 更新地鼠
for mole in moles:
mole.update()
# 绘制画面
screen.fill((255, 255, 255))
for mole in moles:
if mole.visible:
pygame.draw.circle(screen, (255, 0, 0), (mole.x, mole.y), 50)
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), 1, (0, 0, 0))
screen.blit(score_text, (10, 10))
time_left = GAME_TIME - (time.time() - start_time)
time_text = font.render("Time Left: " + str(int(time_left)), 1, (0, 0, 0))
screen.blit(time_text, (WIDTH - 150, 10))
pygame.display.flip()
# 判断游戏是否结束
if time_left <= 0:
game_over = True
# 显示最终得分
font = pygame.font.Font(None, 72)
score_text = font.render("Final Score: " + str(score), 1, (0, 0, 0))
screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - score_text.get_height() // 2))
pygame.display.flip()
# 等待退出
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
```
注意:这个代码需要使用 Pygame 库。请确保您已经安装了它。
阅读全文