中秋将至利用python画一些月饼从天而降不用买了
作者:顾木子吖 发布时间:2023-08-17 13:08:23
标签:python,中秋,月饼,游戏
导语
好消息!下一个假期已经在路上了,正在向我们招手呢!
大家只要再坚持5天
就能迎来中秋小长假啦~
“海上生明月,天涯共此时”
又是一年中秋至!快跟着小编来看看怎么寓教于乐吧~~
今天带大家编写一款应时应景的中秋小游戏!
天上掉月饼啦~天上掉月饼啦~天上掉月饼啦~
准备好相应的素材如下:
环境安装:
Python3.6、pycharm2021、游戏模块Pygame。
安装:pip install pygame
初始化游戏加载素材:
def initGame():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('中秋月饼小游戏')
game_images = {}
for key, value in cfg.IMAGE_PATHS.items():
if isinstance(value, list):
images = []
for item in value: images.append(pygame.image.load(item))
game_images[key] = images
else:
game_images[key] = pygame.image.load(value)
game_sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
if key == 'bgm': continue
game_sounds[key] = pygame.mixer.Sound(value)
return screen, game_images, game_sounds
主函数定义:
def main():
# 初始化
screen, game_images, game_sounds = initGame()
# 播放背景音乐
pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
pygame.mixer.music.play(-1, 0.0)
# 字体加载
font = pygame.font.Font(cfg.FONT_PATH, 40)
# 定义hero
hero = Hero(game_images['hero'], position=(375, 520))
# 定义掉落组
food_sprites_group = pygame.sprite.Group()
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
# 当前分数/历史最高分
score = 0
highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
# 游戏主循环
clock = pygame.time.Clock()
while True:
# --填充背景
screen.fill(0)
screen.blit(game_images['background'], (0, 0))
# --倒计时信息
countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
countdown_text = font.render(countdown_text, True, (0, 0, 0))
countdown_rect = countdown_text.get_rect()
countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]
screen.blit(countdown_text, countdown_rect)
# --按键检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
hero.move(cfg.SCREENSIZE, 'left')
if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
hero.move(cfg.SCREENSIZE, 'right')
# --随机生成
generate_food_count += 1
if generate_food_count > generate_food_freq:
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
food_sprites_group.add(food)
# --更新掉落
for food in food_sprites_group:
if food.update(): food_sprites_group.remove(food)
# --碰撞检测
for food in food_sprites_group:
if pygame.sprite.collide_mask(food, hero):
game_sounds['get'].play()
food_sprites_group.remove(food)
score += food.score
if score > highest_score: highest_score = score
# --画hero
hero.draw(screen)
# --画
food_sprites_group.draw(screen)
# --显示得分
score_text = f'Score: {score}, Highest: {highest_score}'
score_text = font.render(score_text, True, (0, 0, 0))
score_rect = score_text.get_rect()
score_rect.topleft = [5, 5]
screen.blit(score_text, score_rect)
# --判断游戏是否结束
if pygame.time.get_ticks() >= 90000:
break
# --更新屏幕
pygame.display.flip()
clock.tick(cfg.FPS)
# 游戏结束, 记录最高分并显示游戏结束画面
fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
fp.write(str(highest_score))
fp.close()
return showEndGameInterface(screen, cfg, score, highest_score)
定义月饼、灯笼等掉落:
import pygame
import random
class Food(pygame.sprite.Sprite):
def __init__(self, images_dict, selected_key, screensize, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.screensize = screensize
self.image = images_dict[selected_key]
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
self.rect.left, self.rect.bottom = random.randint(20, screensize[0]-20), -10
self.speed = random.randrange(5, 10)
self.score = 1 if selected_key == 'gold' else 5
'''更新食物位置'''
def update(self):
self.rect.bottom += self.speed
if self.rect.top > self.screensize[1]:
return True
return False
定义接月饼的人物:
import pygame
class Hero(pygame.sprite.Sprite):
def __init__(self, images, position=(375, 520), **kwargs):
pygame.sprite.Sprite.__init__(self)
self.images_right = images[:5]
self.images_left = images[5:]
self.images = self.images_right.copy()
self.image = self.images[0]
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
self.diretion = 'right'
self.speed = 8
self.switch_frame_count = 0
self.switch_frame_freq = 1
self.frame_index = 0
'''左右移动hero'''
def move(self, screensize, direction):
assert direction in ['left', 'right']
if direction != self.diretion:
self.images = self.images_left.copy() if direction == 'left' else self.images_right.copy()
self.image = self.images[0]
self.diretion = direction
self.switch_frame_count = 0
self.switch_frame_count += 1
if self.switch_frame_count % self.switch_frame_freq == 0:
self.switch_frame_count = 0
self.frame_index = (self.frame_index + 1) % len(self.images)
self.image = self.images[self.frame_index]
if direction == 'left':
self.rect.left = max(self.rect.left-self.speed, 0)
else:
self.rect.left = min(self.rect.left+self.speed, screensize[0])
'''画到屏幕上'''
def draw(self, screen):
screen.blit(self.image, self.rect)
游戏结束界面:设置的一分30秒结束接到多少就是多少分数。
import sys
import pygame
'''游戏结束画面'''
def showEndGameInterface(screen, cfg, score, highest_score):
# 显示的文本信息设置
font_big = pygame.font.Font(cfg.FONT_PATH, 60)
font_small = pygame.font.Font(cfg.FONT_PATH, 40)
text_title = font_big.render(f"Time is up!", True, (255, 0, 0))
text_title_rect = text_title.get_rect()
text_title_rect.centerx = screen.get_rect().centerx
text_title_rect.centery = screen.get_rect().centery - 100
text_score = font_small.render(f"Score: {score}, Highest Score: {highest_score}", True, (255, 0, 0))
text_score_rect = text_score.get_rect()
text_score_rect.centerx = screen.get_rect().centerx
text_score_rect.centery = screen.get_rect().centery - 10
text_tip = font_small.render(f"Enter Q to quit game or Enter R to restart game", True, (255, 0, 0))
text_tip_rect = text_tip.get_rect()
text_tip_rect.centerx = screen.get_rect().centerx
text_tip_rect.centery = screen.get_rect().centery + 60
text_tip_count = 0
text_tip_freq = 10
text_tip_show_flag = True
# 界面主循环
clock = pygame.time.Clock()
while True:
screen.fill(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return False
elif event.key == pygame.K_r:
return True
screen.blit(text_title, text_title_rect)
screen.blit(text_score, text_score_rect)
if text_tip_show_flag:
screen.blit(text_tip, text_tip_rect)
text_tip_count += 1
if text_tip_count % text_tip_freq == 0:
text_tip_count = 0
text_tip_show_flag = not text_tip_show_flag
pygame.display.flip()
clock.tick(cfg.FPS)
游戏界面:
总结
好啦!今天的游戏更新跟中秋主题一次性写完啦!嘿嘿~机智如我!
来源:https://blog.csdn.net/weixin_55822277/article/details/120323576


猜你喜欢
- 前言Pillow库有很多用途,本文使用Pillow来生成随机的验证码图片。Pillow的用法参考:https://www.jb51.net/
- 前言本文给大家深入的解答了关于Python的11道基本面试题,通过这些面试题大家能对python进一步的了解和学习,下面话不多说,来看看详细
- 好久没写技术相关的文章,这次写篇有意思的,关于一个有意思的游戏——QQ找茬,关于一种有意思的语言——Python,关于一个有意思的库——Qt
- 在安装完数据库后,由于自己不小心直接关闭了安装窗口,或者长时间没有使用root用户登录系统,导致忘记了root密码,这时就需要重置MySQL
- vue页面的打印和下载PDF(加水印)vue项目页面的打印打印的不用说,调用 window.print() 的方法即可;注意点:如果用到背景
- 如何通过Kerberos认证.1.安装Kerberos客户端CentOS:yum install krb5-workstation使用whi
- Go 程序的性能优化及 pprof 的使用程序的性能优化无非就是对程序占用资源的优化。对于服务器而言,最重要的两项资源莫过于 CPU 和内存
- 一、CNN简介1. 神经网络基础输入层(Input layer),众多神经元(Neuron)接受大量非线形输入讯息。输入的讯息称为输入向量。
- 各种asp字符串处理函数,包括:把字符串换为char型数组,把一个数组转换成一个字符串,检查源字符串str是否以chars开头,检查源字符串
- 一条记录可以看做一条数据的数组1 Html1.1 批量选择框1.2&
- 最近写一个BootStrap页面...因为功能需要所以决定一个页面解决所有问题,然后用jQuery来动态显示功能....然而这样做的话页面会
- 本文实例分析了CI框架出现mysql数据库连接资源无法释放的解决方法。分享给大家供大家参考,具体如下:使用ci框架提供的类查询数据:$thi
- 如果用户查询时,使用Order BY排序语句指定按员工编号来排序,那么排序后产生的所有记录就是临时数据。对于这些临时数据,Oracle数据库
- Pivot 及 Pivot_table函数用法Pivot和Pivot_table函数都是对数据做透视表而使用的。其中的区别在于Pivot_t
- 每当重大节日期间,各大主流网站首页会披上节日的盛装,设计者一般会使用大幅背景图片来获得更好的视觉冲击效果,当然,也要考虑到有些用户不习惯这大
- python中.split()只能用指定一个分隔符例如:text='3.14:15'print text.split(
- 最早大家都没有给链接加title的习惯,后来因为w3c标准普及,又集体加上了title。从一个极端走到另个极端,于是出现很多怪异现象。两方面
- 第一步:获取mysql YUM源进入mysql官网获取RPM包下载地址https://dev.mysql.com/downloads/rep
- 上篇文章分享了windows下载mysql5.7压缩包配置安装mysql后续可以选择①在本地创建一个数据库,使用navicat工具导出远程测
- 相信大家在日常学习或者是阅读英文文章的过程中,难免会出现几个不认识的单词,或者想快速翻译某段英文的意思。今天,利用Python爬虫等知识,教