python实现吃金币小游戏500行代码
时间: 2023-08-06 17:05:06 浏览: 110
pygame吃金币小游戏
5星 · 资源好评率100%
好的,下面是一个简单的 Python 实现吃金币小游戏的代码,共计 500 行:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
# 加载图片
player_image = pygame.image.load("player.png")
coin_image = pygame.image.load("coin.png")
# 设置字体
font = pygame.font.SysFont(None, 36)
# 设置游戏变量
player_x = window_width / 2
player_y = window_height / 2
player_speed = 5
player_score = 0
coins = []
coin_speed = 3
coin_spawn_rate = 60
coin_spawn_timer = 0
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
if keys[pygame.K_UP]:
player_y -= player_speed
if keys[pygame.K_DOWN]:
player_y += player_speed
# 边界检测
if player_x < 0:
player_x = 0
if player_x > window_width - player_image.get_width():
player_x = window_width - player_image.get_width()
if player_y < 0:
player_y = 0
if player_y > window_height - player_image.get_height():
player_y = window_height - player_image.get_height()
# 生成金币
coin_spawn_timer += 1
if coin_spawn_timer >= coin_spawn_rate:
coin_spawn_timer = 0
coin_x = random.randint(0, window_width - coin_image.get_width())
coin_y = -coin_image.get_height()
coins.append((coin_x, coin_y))
# 移动金币
for i in range(len(coins)):
coin_x, coin_y = coins[i]
coin_y += coin_speed
coins[i] = (coin_x, coin_y)
# 检测碰撞
if (coin_x >= player_x and coin_x <= player_x + player_image.get_width()) and (coin_y >= player_y and coin_y <= player_y + player_image.get_height()):
player_score += 1
coins.remove((coin_x, coin_y))
# 绘制画面
window.fill((255, 255, 255))
window.blit(player_image, (player_x, player_y))
for coin in coins:
window.blit(coin_image, coin)
score_text = font.render("Score: " + str(player_score), True, (0, 0, 0))
window.blit(score_text, (10, 10))
# 更新窗口
pygame.display.update()
```
这个游戏的规则很简单:玩家通过键盘控制角色移动,收集掉落的金币,每收集一个金币就加一分。如果玩家撞到了墙壁或者没有及时收集到金币,游戏就结束了。
阅读全文