Python吃金币小游戏源代码
时间: 2023-08-03 08:04:38 浏览: 180
一个吃金币的小游戏(源码)
5星 · 资源好评率100%
这是一个简单的Python小游戏,它可以让一个小人吃金币并得分。以下是游戏的源代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (50, 153, 213)
YELLOW = (255, 255, 0)
# 设置屏幕宽高
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
# 创建屏幕
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置游戏标题
pygame.display.set_caption('Python吃金币小游戏')
# 加载小人图像
player_image = pygame.image.load('player.png').convert()
player_image.set_colorkey(WHITE)
# 加载金币图像
coin_image = pygame.image.load('coin.png').convert()
coin_image.set_colorkey(WHITE)
# 设置字体
font = pygame.font.SysFont('Calibri', 25, True, False)
# 定义金币列表
coin_list = []
# 生成金币函数
def create_coin():
coin = {
'x': random.randint(0, SCREEN_WIDTH - 50),
'y': random.randint(0, SCREEN_HEIGHT - 50)
}
coin_list.append(coin)
# 主程序
def main():
# 初始化分数
score = 0
# 初始化小人位置
player_x = 0
player_y = 0
# 创建金币
for i in range(10):
create_coin()
# 游戏主循环
done = False
clock = pygame.time.Clock()
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 获取键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= 5
elif keys[pygame.K_RIGHT]:
player_x += 5
elif keys[pygame.K_UP]:
player_y -= 5
elif keys[pygame.K_DOWN]:
player_y += 5
# 绘制背景
screen.fill(BLUE)
# 绘制金币
for coin in coin_list:
screen.blit(coin_image, [coin['x'], coin['y']])
# 绘制小人
screen.blit(player_image, [player_x, player_y])
# 检测是否碰到金币
for coin in coin_list:
if player_x < coin['x'] + 50 and player_x + 50 > coin['x'] and player_y < coin['y'] + 50 and player_y + 50 > coin['y']:
coin_list.remove(coin)
score += 1
create_coin()
# 绘制分数
text = font.render('Score: ' + str(score), True, YELLOW)
screen.blit(text, [10, 10])
# 刷新屏幕
pygame.display.flip()
# 设置帧率
clock.tick(60)
# 关闭Pygame
pygame.quit()
if __name__ == '__main__':
main()
```
请注意,此代码假定您已经有了两个图像文件(player.png和coin.png),它们应该与代码文件位于同一目录中。
阅读全文