python打地鼠游戏代码
时间: 2023-07-09 15:37:47 浏览: 77
打地鼠游戏代码
以下是一个简单的Python打地鼠游戏代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
WINDOW_SIZE = [WINDOW_WIDTH, WINDOW_HEIGHT]
screen = pygame.display.set_mode(WINDOW_SIZE)
# 设置游戏标题
pygame.display.set_caption("Whack-a-Mole")
# 加载游戏资源
BACKGROUND_IMAGE = pygame.image.load("background.jpg")
MOLE_IMAGE = pygame.image.load("mole.png")
HAMMER_IMAGE = pygame.image.load("hammer.png")
WHACK_SOUND = pygame.mixer.Sound("whack.wav")
# 设置游戏参数
MOLE_WIDTH = 100
MOLE_HEIGHT = 100
MOLE_SPEED = 5
HAMMER_WIDTH = 100
HAMMER_HEIGHT = 100
SCORE = 0
FONT = pygame.font.SysFont("Arial", 24)
# 定义地鼠类
class Mole(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = MOLE_IMAGE
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WINDOW_WIDTH - MOLE_WIDTH)
self.rect.y = random.randint(0, WINDOW_HEIGHT - MOLE_HEIGHT)
self.speed = MOLE_SPEED
def update(self):
self.rect.y += self.speed
if self.rect.y > WINDOW_HEIGHT:
self.kill()
# 定义锤子类
class Hammer(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = HAMMER_IMAGE
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
def update(self):
mouse_pos = pygame.mouse.get_pos()
self.rect.x = mouse_pos[0]
self.rect.y = mouse_pos[1]
# 创建地鼠和锤子精灵组
mole_group = pygame.sprite.Group()
hammer_group = pygame.sprite.Group()
# 创建地鼠和锤子实例,并添加到精灵组中
for i in range(10):
mole = Mole()
mole_group.add(mole)
hammer = Hammer()
hammer_group.add(hammer)
# 设置游戏循环
running = True
clock = pygame.time.Clock()
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 检测是否击中地鼠
hammer_hit_list = pygame.sprite.spritecollide(hammer_group.sprites()[0], mole_group, False)
if len(hammer_hit_list) > 0:
SCORE += 1
WHACK_SOUND.play()
mole_group.remove(hammer_hit_list[0])
hammer_group.empty()
hammer_group.add(Hammer())
# 更新游戏状态
mole_group.update()
hammer_group.update()
# 绘制游戏界面
screen.blit(BACKGROUND_IMAGE, [0, 0])
mole_group.draw(screen)
hammer_group.draw(screen)
score_text = FONT.render("Score: {}".format(SCORE), True, (255, 255, 255))
screen.blit(score_text, [10, 10])
# 刷新游戏界面
pygame.display.flip()
# 设置游戏帧率
clock.tick(60)
# 退出Pygame
pygame.quit()
```
这是一个基本的打地鼠游戏代码示例,你可以根据自己的需求进行修改和扩展。
阅读全文