给我写一个有敌人和地图的python吃豆人小游戏
时间: 2024-05-15 12:12:11 浏览: 155
关于吃豆人的游戏代码(python)
5星 · 资源好评率100%
好的,以下是一个简单的Python吃豆人小游戏,包含敌人和地图。
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口大小
screen_width = 640
screen_height = 480
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("吃豆人小游戏")
# 加载资源
player_image = pygame.image.load("player.png")
enemy_image = pygame.image.load("enemy.png")
dot_image = pygame.image.load("dot.png")
# 定义游戏元素类
class Element(pygame.sprite.Sprite):
def __init__(self, image, x, y):
super().__init__()
self.image = image
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 定义玩家类
class Player(Element):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.speed = 3
def move(self, dx, dy):
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
# 定义敌人类
class Enemy(Element):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.speed = 2
self.direction = random.choice(["up", "down", "left", "right"])
def move(self):
if self.direction == "up":
self.rect.y -= self.speed
elif self.direction == "down":
self.rect.y += self.speed
elif self.direction == "left":
self.rect.x -= self.speed
elif self.direction == "right":
self.rect.x += self.speed
if self.rect.left < 0 or self.rect.right > screen_width or self.rect.top < 0 or self.rect.bottom > screen_height:
self.direction = random.choice(["up", "down", "left", "right"])
# 定义豆子类
class Dot(Element):
def __init__(self, image, x, y):
super().__init__(image, x, y)
# 创建游戏元素组
all_sprites = pygame.sprite.Group()
dots = pygame.sprite.Group()
enemies = pygame.sprite.Group()
# 创建玩家实例
player = Player(player_image, screen_width // 2, screen_height // 2)
all_sprites.add(player)
# 创建豆子实例
for i in range(50):
dot = Dot(dot_image, random.randint(0, screen_width - 20), random.randint(0, screen_height - 20))
all_sprites.add(dot)
dots.add(dot)
# 创建敌人实例
for i in range(5):
enemy = Enemy(enemy_image, random.randint(0, screen_width - 20), random.randint(0, screen_height - 20))
all_sprites.add(enemy)
enemies.add(enemy)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.move(-1, 0)
elif keys[pygame.K_RIGHT]:
player.move(1, 0)
elif keys[pygame.K_UP]:
player.move(0, -1)
elif keys[pygame.K_DOWN]:
player.move(0, 1)
# 移动敌人
for enemy in enemies:
enemy.move()
# 碰撞检测
for dot in pygame.sprite.spritecollide(player, dots, True):
dots.remove(dot)
all_sprites.remove(dot)
for enemy in pygame.sprite.spritecollide(player, enemies, False):
running = False
# 更新画面
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
这个小游戏包含了玩家、敌人和豆子三种游戏元素,玩家通过键盘控制移动,敌人随机移动并会与玩家碰撞,豆子会被玩家吃掉。你可以自行替换图片和调整游戏元素的数量、速度和大小等参数。
阅读全文