pycharm打地鼠游戏代码
时间: 2023-11-29 08:47:16 浏览: 100
以下是使用Pygame模块在Pycharm中编写的打地鼠游戏代码:
```python
import pygame
import sys
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
# 设置游戏窗口标题
pygame.display.set_caption("打地鼠游戏")
# 加载背景图片
bg_image = pygame.image.load("background.jpg").convert()
# 加载地鼠图片
mouse_image = pygame.image.load("mouse.png").convert_alpha()
# 设置游戏帧率
clock = pygame.time.Clock()
FPS = 10
# 设置字体
font = pygame.font.Font(None, 36)
# 设置游戏得分
score = 0
# 设置游戏结束标志
game_over = False
# 地鼠类
class Mouse(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = mouse_image
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = random.randint(0, width - self.rect.width), random.randint(0, height - self.rect.height)
def update(self):
self.rect.left, self.rect.top = random.randint(0, width - self.rect.width), random.randint(0, height - self.rect.height)
# 创建地鼠组
mouse_group = pygame.sprite.Group()
for i in range(10):
mouse = Mouse()
mouse_group.add(mouse)
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# 判断是否点中地鼠
for mouse in mouse_group:
if mouse.rect.collidepoint(event.pos):
mouse_group.remove(mouse)
score += 10
# 更新地鼠
mouse_group.update()
# 绘制游戏界面
screen.blit(bg_image, (0, 0))
mouse_group.draw(screen)
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 判断游戏是否结束
if len(mouse_group) == 0:
game_over = True
game_over_text = font.render("Game Over!", True, (255, 0, 0))
screen.blit(game_over_text, (width // 2 - game_over_text.get_width() // 2, height // 2 - game_over_text.get_height() // 2))
# 刷新游戏界面
pygame.display.flip()
# 控制游戏帧率
clock.tick(FPS)
# 退出Pygame
pygame.quit()
```
阅读全文