python吃金币小游戏代码

一个简单的Python吃金币小游戏的代码示例。这个游戏使用了Pygame库来创建窗口和处理用户输入,并使用了一些基本的图形操作来显示金币和玩家的位置。

import pygame

import sys

import random

# 初始化Pygame

pygame.init()

# 设置窗口大小

screen_width = 800

screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏时钟

clock = pygame.time.Clock()

# 加载图像

player_image = pygame.image.load('player.png').convert_alpha()

coin_image = pygame.image.load('coin.png').convert_alpha()

# 定义玩家的初始位置

player_x = 50

player_y = 50

# 定义金币列表

coins = []

# 游戏循环标志

running = True

# 生成金币

def generate_coin():

coin_x = random.randint(10, screen_width - 10)

coin_y = random.randint(10, screen_height - 10)

coins.append([coin_x, coin_y])

# 玩家移动

def move_player():

global player_x, player_y

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:

player_x -= 5

if keys[pygame.K_RIGHT]:

player_x += 5

if keys[pygame.K_UP]:

player_y -= 5

if keys[pygame.K_DOWN]:

player_y += 5

# 玩家边界检查

def check_bounds():

global player_x, player_y

if player_x < 10:

player_x = 10

if player_y < 10:

player_y = 10

if player_x > screen_width - 10:

player_x = screen_width - 10

if player_y > screen_height - 10:

player_y = screen_height - 10

# 游戏逻辑

while running:

# 设置背景颜色

screen.fill((255, 255, 255))

# 事件处理

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

# 生成金币

generate_coin()

# 玩家移动

move_player()

# 边界检查

check_bounds()

# 绘制玩家

screen.blit(player_image, (player_x, player_y))

# 绘制金币

for coin in coins:

screen.blit(coin_image, (coin[0], coin[1]))

# 玩家吃金币

if player_x < coin[0] + coin_image.get_width() and player_x + player_image.get_width() > coin[0]:

if player_y < coin[1] + coin_image.get_height() and player_y + player_image.get_height() > coin[1]:

coins.remove(coin)

# 更新屏幕

pygame.display.flip()

# 控制游戏速度

clock.tick(60)

# 退出Pygame

pygame.quit()

# 退出系统

sys.exit()

在这个代码中,你需要自己准备两张图片:一张是玩家的图片(player.png),另一张是金币的图片(coin.png)。你可以根据自己的需要修改图片的路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值