wordpress如何设置网站描述,上传网站过程,鸿鹄网站建设,俄罗斯免费服务器python和pygame实现捉小兔游戏 python和pygame实现捉小兔游戏#xff0c;需要安装使用第三方库pygame#xff0c;关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520
下面是使用Python和Pygame创建的游戏#xff0c;其中有…python和pygame实现捉小兔游戏 python和pygame实现捉小兔游戏需要安装使用第三方库pygame关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520
下面是使用Python和Pygame创建的游戏其中有一个草地背景图片和一个随机移动的小图片——小兔子玩家要使用鼠标点击小兔子小图片每次点击成功代表捉到一只小兔子成绩Score加一分。成绩的右边有计时器以秒为单位来显示游戏的运行时间。
先看效果图 需要两张图片素材
background.jpg图片如下 small_image.jpg图片如下 请注意上述代码假定背景图片为background.jpg小图片为small_image.png。请确保将这两个文件与下面给出源码文件放在同一目录下。你可以自行替换这些图片只需确保文件名正确。
下面给出源码
import pygame
import random
import time# 初始化游戏
pygame.init()# 设置游戏窗口尺寸
WIDTH 800
HEIGHT 600
window pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(捉小兔游戏用鼠标点击)# 加载背景图片
background_img pygame.image.load(background.jpg)# 加载小图片
small_img pygame.image.load(small_image.jpg)
small_rect small_img.get_rect()# 设置小图片的初始位置
small_rect.x random.randint(0, WIDTH - small_rect.width)
small_rect.y random.randint(0, HEIGHT - small_rect.height)# 初始化得分
score 0
# 计时器
start_time time.time()# 游戏主循环
running True
clock pygame.time.Clock()while running:for event in pygame.event.get():if event.type pygame.QUIT:running Falseelif event.type pygame.MOUSEBUTTONDOWN:# 检查是否点击到了小图片if small_rect.collidepoint(event.pos):# 点击成功得分加一score 1# 重新设置小图片的位置small_rect.x random.randint(0, WIDTH - small_rect.width)small_rect.y random.randint(0, HEIGHT - small_rect.height)# 移动小图片small_rect.x random.randint(-35, 35) #small_rect.y random.randint(-35, 35) ## 确保小图片在窗口内部if small_rect.left 0:small_rect.left 0if small_rect.right WIDTH:small_rect.right WIDTHif small_rect.top 0:small_rect.top 0if small_rect.bottom HEIGHT:small_rect.bottom HEIGHT# 更新背景图片window.blit(background_img, (0, 0))# 更新小图片window.blit(small_img, (small_rect.x, small_rect.y))# 显示得分font pygame.font.Font(None, 36)score_text font.render(Score: str(score), True, (255, 0, 0)) #window.blit(score_text, (10, 10))# 显示计时器elapsed_time int(time.time() - start_time)time_text font.render(Time: str(elapsed_time) s, True, (255, 0, 0))window.blit(time_text, (WIDTH - 150, 10))# 刷新窗口pygame.display.flip()# 添加延迟时间处理小图移动太快晃眼pygame.time.delay(200) #200毫秒# 控制游戏帧率clock.tick(60)# 退出游戏
pygame.quit()