要把上述代码中的游戏角色替换为葫芦娃,你需要准备好葫芦娃的图片,并将其加载到游戏中。
以下是修改后的代码,将游戏角色替换为葫芦娃:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口的大小
window_width = 400
window_height = 600
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('My Game')
# 时钟控制
clock = pygame.time.Clock()
# 加载图片
player_image = pygame.image.load('huluwa.png')
player_width = 50
player_height = 50
# 障碍物列表
obstacles = []
# 添加障碍物
def add_obstacle():
obstacle_width = 60
obstacle_height = 40
obstacle_x = random.randint(0, window_width - obstacle_width)
obstacle_y = -obstacle_height
obstacle_speed = random.randint(1, 5)
obstacles.append({'x': obstacle_x, 'y': obstacle_y, 'speed': obstacle_speed, 'width': obstacle_width, 'height': obstacle_height})
# 碰撞检测
def is_collision(player_x, player_y, player_width, player_height, obstacle_x, obstacle_y, obstacle_width, obstacle_height):
if player_x + player_width > obstacle_x and player_x < obstacle_x + obstacle_width:
if player_y + player_height > obstacle_y and player_y < obstacle_y + obstacle_height:
return True
return False
# 游戏循环
def game_loop():
player_x = window_width / 2 - player_width / 2
player_y = window_height - player_height
player_speed = 5
score = 0
game_exit = False
while not game_exit:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
# 移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < window_width - player_width:
player_x += player_speed
# 添加障碍物
if random.randint(0, 100) < 5:
add_obstacle()
# 移动障碍物
for obstacle in obstacles:
obstacle['y'] += obstacle['speed']
# 检测碰撞
if is_collision(player_x, player_y, player_width, player_height, obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']):
game_exit = True
# 删除越界的障碍物
if obstacle['y'] > window_height:
obstacles.remove(obstacle)
score += 1
# 绘制游戏界面
game_display.fill(white)
# 绘制玩家
game_display.blit(player_image, (player_x, player_y))
# 绘制障碍物
for obstacle in obstacles:
pygame.draw.rect(game_display, red, (obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']))
# 显示分数
font = pygame.font.SysFont(None, 25)
text = font.render('Score: ' + str(score), True, black)
game_display.blit(text, (10, 10))
pygame.display.update()
# 控制帧率
clock.tick(60)
pygame.quit()
quit()
game_loop()
```
在这个修改后的代码中,我们将玩家的图片替换为了葫芦娃,并将其命名为'huluwa.png'。这个图片应该放在与代码文件相同的目录下,以便程序正确地加载它。