• 【Python小系统】四级考满分的学姐告诉你这样学英语逢考必过,赶紧康康叭~(捷径分享)


    导语

    哈喽哈喽!很久没更新啦,有没有小伙伴儿想我呀~(举手🙋‍)

    今天开始恢复更新啦——希望大家多多支持,爆文我就爆更哦~嘿嘿嘿👇

    1. A Deep-sworn Vow
    2. Others because you did notkeep,
    3. That deep-sworn vow have beenfriends of mine;
    4. Yet always when I look death in the face,
    5. When I clamber to the heightsof sleep,
    6. Or when I grow excited withwine,
    7. Suddenly I meet your face.
    8. ——John Keats

    (这是木子分享给大家的一首小诗,想知道这段小诗的中文意思吗?在文末哦~)

    所有文章完整的素材+源码都在👇👇

    粉丝白嫖源码福利,请移步至CSDN社区或文末公众hao即可免费。

    相信大家对于英语四级一点都不陌生了吧?

    很多学校都是要求学生必须考过英语四级,不然就不能毕业。

    一开始我抱着侥幸心理,心想上高中的时候英语不错,四级应该也很容易。不过成

    绩出来我就傻眼了,没有通过。然后我就制定了周密的学习计划,开始有计划地学习英语,等

    到第二次考试的时候终于通过啦。今天,小编给大家制作一款Python编程代码版本的四级考试

    打字小游戏,边玩儿游戏还能复习单词还能保持学习的积极性,这款代码游戏真的是考级姐妹

    的灵魂首先,让我们开正式康康叭👇

    ​正文

    一、敲代码之前的小tips——(仅个人观点勿喷)

    四级之前,大家要很认真的备考啦,每天做做各种类型的四级题,可以量不多,但是会用心的

    做,做完之后都会认真的总结,就算那种不仔细的原因也会写在错题旁边,借以提醒自己。每

    天这样去做的原因就是保持题感,毕竟四级是一门考试,好多题还是有很多套路的,但只要持

    之以恒地去联系,虽然套路深,铁杵磨成针

     

     听力方面:每次听完并对过答案之后会继续听那一份听力材料,因为第一次是泛听,只需要抓

    住关键词的信息成功get到答案就好,那么后面就要开始精听,这一次我们的目标就是听懂这个

    人到底在说什么,争取听懂每一句,好了,接下来,当我反复听一句话却怎么也听不懂其中的

    某几个词的时候,那我就找到可以收入宝囊的法器了,然后你就把这几个词好好地在牛津字典

    里查一查,记在自己的收集本上,还要多多巩固,因为这些词语出现在考试中,从某种程度上

    来说就属于高频词汇的。另外呢,在精听的时候,我们要多多注意朗读者说英语时的感觉,包

    括他的发音、语调,都很重要,所以也可以跟着他一起读英语,在边听边说的过程中,我们的

    耳朵对英语会更加地敏感。

    阅读方面:在就应对四级考试的时候,刷题当然是不二选择,前面已经提到过四级套路深,所

    以考试之前,我每天大概会做一篇阅读,设定时间是很重要的,这样可以把握自己的考试节

    奏,不会太慌张。四级阅读题,一般都会按照文章的顺序来设计题目,一般情况下,四级阅读

    题的内容不会太少,信息量比较多,而我需要的又仅仅只是那几条有用的信息。那么,首先就

    先看文章后面的问题,带着问题去读文章,会起到事半功倍的效果,也节省时间。做完一篇阅

    读之后,需要认真总结错误原因,那么你错的题就错得很有意义,如果只是不停地做题,而不

    停下来反思原因,那做一万道题也不如做一道题。总结错误之后,同样需要仔细查阅陌生的单

    词,不断积累,方可在英语阅读中做到游刃有余。

    写作翻译方面:毋庸置疑,它们都是一种全面输出的体现,因此,更需要扎实地进行练习。我

    在四级考试之前,会准备一个本子,认真写好每一篇作文或是翻译,字迹工整,仔细构思,写

    完以后和优秀范文对比,学习它的用法,在平时就养成好的习惯,到了考场上才会更加从容。

    我觉得,写得越多,就会写得越好,优美而实用的句型才会信手拈来。总之,这同样是个坚持

    的过程,但终究会破茧成蝶、妙笔生花的。

    二、运行环境

    小编使用的环境:Python3、Pycharm社区版、Pygame模块。内置模块 你安装 好python环

    境就可以了。

     模块安装:pip install -i https://pypi.douban.com/simple/ +pygame

    三、素材(图片等)

    图片多,装不下,仅部分哈👇(懒.jpg)还有字体,音乐背景等等都没展示了哈。

    下面是提前准备的单词,大家每天可以更新一下的哈如下几百个是我准备的👇截图部分。

    四、代码展示

    1)主程序(英文打字小游戏主入口模块)

    1. # !/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. """
    4. Author: 顾木子吖
    5. """
    6. import os
    7. import sys
    8. import time
    9. import traceback
    10. import Game_View
    11. from Game_View import *
    12. from Game_Sprite import *
    13. def center_pos():
    14. """设置游戏窗口相对电脑屏幕居中"""
    15. game_x = (Game_Info.SCREEN_X - Game_Info.SCREEN_RECT.width) / 2
    16. game_y = (Game_Info.SCREEN_Y - Game_Info.SCREEN_RECT.height) / 2
    17. os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (game_x, game_y)
    18. def random_music():
    19. """随机播放背景音乐"""
    20. # 判断是否是静音模式
    21. print(Game_View.GameStartWin.voice_flag())
    22. try:
    23. pygame.mixer.init()
    24. pygame.mixer.music.load(random.choice(Game_Info.GAME_MUSICS))
    25. pygame.mixer.music.play(loops=0)
    26. except Exception as e:
    27. print("无法加载音频,请检查电脑配置" + str(e))
    28. print(traceback.format_exc())
    29. if not Game_View.GameStartWin.voice_flag():
    30. pygame.mixer_music.set_volume(0)
    31. def parser_words() -> dict:
    32. """
    33. 解析英语单词
    34. :return {"eng_word": val, "cn_comment": val}
    35. """
    36. english_words = []
    37. word_contents = open(Game_Info.GAME_WORD_TEXT, encoding="gbk")
    38. for value in word_contents:
    39. value = value.lstrip()
    40. word_list = value.split(" ")
    41. words = [i for i in word_list if i != '']
    42. if len(words) >= 2:
    43. # 把解析好的单词和注释封装到字典中,然后加入列表
    44. english_words.append(
    45. {"eng_word": words[0], "cn_comment": words[1]})
    46. return english_words
    47. class TypingGame(object):
    48. """打字游戏主类"""
    49. spell_ok = False # 用于标识单词拼写成功
    50. game_pause_flag = False # 游戏暂停标志
    51. game_over_flag = False # 游戏结束标志
    52. game_quit_flag = False # 游戏退出标志
    53. game_total_blood = Game_Info.GAME_BLOOD_RECT.width # 游戏总能量(血条)
    54. # 游戏等级对照字典
    55. game_level_dict = {
    56. 1: {"word_fall_speed": 0.3, "level_text": u"简单", "level_color": "green"},
    57. 2: {"word_fall_speed": 0.5, "level_text": u"上手", "level_color": "blue"},
    58. 3: {"word_fall_speed": 1.0, "level_text": u"中等", "level_color": "orange"},
    59. 4: {"word_fall_speed": 1.5, "level_text": u"困难", "level_color": "red"},
    60. 5: {"word_fall_speed": 2.0, "level_text": u"魔鬼", "level_color": "purple"}
    61. }
    62. @staticmethod
    63. def game_init():
    64. """游戏初始化"""
    65. # 初始化游戏字体
    66. pygame.font.init()
    67. # 设置游戏标题和图标
    68. pygame.display.set_caption(Game_Info.GAME_NAME)
    69. pygame.display.set_icon(pygame.image.load(Game_Info.GAME_ICON_32))
    70. @staticmethod
    71. def set_game_event():
    72. """设置游戏事件"""
    73. # 设置创建单词的定时器
    74. pygame.time.set_timer(Game_Info.CREATE_WORD_EVENT, Game_Info.CREATE_WORD_INTERVAL)
    75. # 设置游戏音乐结束事件
    76. try:
    77. pygame.mixer.music.set_endevent(Game_Info.MUSIC_END_EVENT)
    78. except Exception as e:
    79. print("无法设置音乐结束事件\t" + str(e))
    80. print(traceback.format_exc())
    81. def __init__(self):
    82. self.words = parser_words()
    83. self.game_conf = GameConfig() # 游戏配置信息
    84. self.game_default_voice = 20 # 游戏默认音量
    85. self.use_time = 0 # 记录游戏使用的时间
    86. self.total_score = 0 # 记录游戏拼写成功了多少个单词
    87. self.word_content = "" # 键盘输入的单词
    88. self.backspace_count = 0 # 回删键按下的次数
    89. # 预先创建动画对象
    90. self.animates = [Animation(self) for _ in range(5)]
    91. # 游戏初始血条值
    92. self.game_blood = int(self.game_conf.game_init_blood) * 10
    93. self.game_clock = pygame.time.Clock()
    94. self.screen = pygame.display.set_mode(Game_Info.SCREEN_RECT.size)
    95. self.game_init()
    96. self.set_game_event() # 设置游戏事件
    97. self.__create_sprite() # 创建游戏精灵
    98. def __create_sprite(self):
    99. """创建精灵和精灵组"""
    100. # 背景精灵
    101. back_sprite = ImageSprite(Game_Info.GAME_BACKGROUND)
    102. # 根据游戏屏幕的大小适配背景图(可能会导致背景图变形)
    103. back_sprite.transform_scale(
    104. back_sprite.image,
    105. (Game_Info.SCREEN_RECT.width, Game_Info.SCREEN_RECT.height)
    106. )
    107. self.back_group = pygame.sprite.Group(back_sprite)
    108. # 英文单词显示框
    109. input_rect_sprite = ImageSprite(Game_Info.INPUT_BACKGROUND)
    110. # 缩放图片
    111. input_rect_sprite.transform_scale(
    112. input_rect_sprite.image,
    113. (Game_Info.INPUT_RECT_WIDTH, Game_Info.INPUT_RECT_HEIGHT)
    114. )
    115. # 水平居中显示
    116. input_rect_sprite.hor_center(Game_Info.SCREEN_RECT)
    117. self.input_rect_group = pygame.sprite.Group(input_rect_sprite)
    118. # 创建“游戏设置”图片
    119. self.game_set_sprite = ImageSprite(Game_Info.GAME_SET_PINK)
    120. set_x = Game_Info.SCREEN_RECT.width - self.game_set_sprite.rect.width - 10
    121. set_y = Game_Info.SCREEN_RECT.height - self.game_set_sprite.rect.height - 10
    122. self.game_set_sprite.set_pos(set_x, set_y)
    123. self.game_set_sprite_group = pygame.sprite.Group(self.game_set_sprite)
    124. # 拼写的单词
    125. spell_word_sprite = SpellSprite(
    126. "",
    127. size=26,
    128. color=pygame.color.Color(self.game_conf.spell_ok_color)
    129. )
    130. spell_word_sprite.hor_center(Game_Info.SCREEN_RECT)
    131. spell_word_sprite.set_pos(spell_word_sprite.rect.x, 40)
    132. self.spell_word_group = pygame.sprite.Group(spell_word_sprite)
    133. # 创建单词精灵组
    134. self.word_group = pygame.sprite.Group()
    135. self.__random_generate_word(Game_Info.GENERATE_WORD_NUM)
    136. # 创建显示游戏时间精灵
    137. time_sprite = TextSprite(text="Time: 0", size=28, color=Game_Info.BLUE)
    138. time_sprite.set_pos(5, 0)
    139. self.time_group = pygame.sprite.Group(time_sprite)
    140. # 游戏分数
    141. self.score_sprite = TextSprite("Score: 0", size=30, color=Game_Info.BLUE)
    142. self.score_sprite.set_pos(Game_Info.SCREEN_RECT.width - self.score_sprite.rect.width - 20, 3)
    143. self.score_group = pygame.sprite.Group(self.score_sprite)
    144. # 游戏结束精灵(组)
    145. self.__game_over_sprite()
    146. def __game_over_sprite(self):
    147. """创建游戏结束的精灵(组)"""
    148. self.game_over_group = pygame.sprite.Group()
    149. game_over_sprite = TextSprite("Game Over", 100, Game_Info.BLUE)
    150. game_over_sprite.rect.y = (Game_Info.SCREEN_RECT.height - game_over_sprite.rect.height - 400) / 2
    151. game_over_sprite.hor_center(Game_Info.SCREEN_RECT)
    152. game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["level_text"]
    153. game_level_color = pygame.color.Color(self.game_level_dict[int(self.game_conf.game_level)]["level_color"])
    154. self.game_level_sprite = TextSprite(u"游戏等级: " + game_level_text, 50, game_level_color)
    155. self.game_level_sprite.rect.y = game_over_sprite.rect.y + 100 + 50
    156. self.game_level_sprite.hor_center(Game_Info.SCREEN_RECT)
    157. self.game_score_sprite = TextSprite(u"游戏分数: ", 50, Game_Info.BLUE)
    158. self.game_score_sprite.rect.y = game_over_sprite.rect.y + 200 + 50
    159. self.game_score_sprite.hor_center(Game_Info.SCREEN_RECT)
    160. self.highest_sprite = TextSprite(u"历史最高: ", 50, Game_Info.BLUE)
    161. self.highest_sprite.rect.y = game_over_sprite.rect.y + 300 + 50
    162. self.highest_sprite.hor_center(Game_Info.SCREEN_RECT)
    163. self.quit_sprite = TextSprite(u"退出", 50, Game_Info.BLUE)
    164. self.quit_sprite.set_pos(
    165. game_over_sprite.rect.x - self.quit_sprite.rect.width,
    166. game_over_sprite.rect.y + 400 + 10
    167. )
    168. self.reset_sprite = TextSprite(u"重 玩", 50, Game_Info.BLUE)
    169. self.reset_sprite.set_pos(
    170. game_over_sprite.rect.x + game_over_sprite.rect.width,
    171. game_over_sprite.rect.y + 400 + 10
    172. )
    173. self.game_over_group.add(
    174. game_over_sprite,
    175. self.game_level_sprite,
    176. self.game_score_sprite,
    177. self.highest_sprite,
    178. self.quit_sprite, self.reset_sprite
    179. )
    180. def __update_sprite(self):
    181. """更新精灵"""
    182. self.back_group.update()
    183. self.back_group.draw(self.screen)
    184. self.game_set_sprite_group.update()
    185. self.game_set_sprite_group.draw(self.screen)
    186. self.input_rect_group.update()
    187. self.input_rect_group.draw(self.screen)
    188. # 计算游戏使用时间
    189. if not self.game_pause_flag and not self.game_over_flag:
    190. self.use_time += 0.1
    191. display_time = "Time: " + str(self.use_time / 6)
    192. self.time_group.update(display_time[:12])
    193. self.time_group.draw(self.screen)
    194. self.score_sprite.set_pos(Game_Info.SCREEN_RECT.width - self.score_sprite.rect.width - 20, 3)
    195. self.score_group.update("Score: " + str(self.total_score))
    196. self.score_group.draw(self.screen)
    197. # 判断是否游戏结束
    198. if self.game_over_flag:
    199. self.__game_over()
    200. game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["level_text"]
    201. self.game_level_sprite.update("游戏等级: " + str(game_level_text))
    202. self.game_over_group.draw(self.screen)
    203. else:
    204. if not self.game_pause_flag:
    205. self.word_group.update(self)
    206. self.word_group.draw(self.screen)
    207. spell_ok_color = pygame.Color(self.game_conf.spell_ok_color)
    208. self.spell_word_group.update(self.word_content, spell_ok_color)
    209. self.spell_word_group.draw(self.screen)
    210. # 更新游戏能量条
    211. if 0 <= self.game_blood <= self.game_total_blood:
    212. self.__draw_game_blood()
    213. # 单词精灵拼写成功动画
    214. for animate in self.animates:
    215. if animate.visible:
    216. animate.draw()
    217. def start_game(self):
    218. """打字游戏开启"""
    219. # 随机播放背景音乐
    220. random_music()
    221. # 利用多线程完成游戏持续掉血
    222. drop_blood_t = threading.Thread(target=self.__drop_blood)
    223. drop_blood_t.start()
    224. while True:
    225. # 是否设置成静音
    226. if not Game_View.GameStartWin.voice_flag():
    227. pygame.mixer_music.set_volume(0)
    228. else:
    229. pygame.mixer_music.set_volume(self.game_default_voice)
    230. # 设置游戏刷新帧率
    231. self.game_clock.tick(Game_Info.FRAME_PRE_SEC)
    232. # 判断游戏结束
    233. if self.game_blood < 0:
    234. TypingGame.game_over_flag = True
    235. else:
    236. self.__animate_action()
    237. self.__check_spell_word()
    238. self.__update_sprite()
    239. self.__event_handle()
    240. pygame.display.update()
    241. def __event_handle(self):
    242. """游戏事件监听"""
    243. # 遍历所有事件
    244. for event in pygame.event.get():
    245. try:
    246. if pygame.mixer.music.get_endevent() == Game_Info.MUSIC_END_EVENT and \
    247. not pygame.mixer.music.get_busy():
    248. # 如果music播放结束且没有音乐在播放就随机下一首
    249. print("下一首")
    250. random_music()
    251. except:
    252. pass
    253. # 如果单击关闭窗口,则退出
    254. if event.type == pygame.QUIT and not self.game_pause_flag:
    255. pygame.quit()
    256. TypingGame.game_quit_flag = True
    257. sys.exit()
    258. # 创建单词事件
    259. elif event.type == Game_Info.CREATE_WORD_EVENT:
    260. if not self.game_over_flag and not self.game_pause_flag:
    261. # 游戏结束或者暂停就停止生成单词了
    262. self.__random_generate_word(word_num=3)
    263. # 鼠标移动事件
    264. elif event.type == pygame.MOUSEMOTION:
    265. x, y = event.pos # 获取屏幕坐标位置
    266. if self.__is_on_set(x, y):
    267. self.game_set_sprite.image = pygame.image.load(Game_Info.GAME_SET_BLUE)
    268. else:
    269. self.game_set_sprite.image = pygame.image.load(Game_Info.GAME_SET_PINK)
    270. # 游戏结束鼠标悬浮在确定按钮上变色
    271. if self.quit_sprite.rect.x <= x <= self.quit_sprite.rect.x + self.quit_sprite.rect.width and \
    272. self.quit_sprite.rect.y <= y <= self.quit_sprite.rect.y + self.quit_sprite.rect.height:
    273. self.quit_sprite.color = Game_Info.PINK
    274. self.quit_sprite.update(self.quit_sprite.text)
    275. else:
    276. self.quit_sprite.color = Game_Info.BLUE
    277. self.quit_sprite.update(self.quit_sprite.text)
    278. # 游戏结束鼠标悬浮在重玩按钮上变色
    279. if self.reset_sprite.rect.x <= x <= self.reset_sprite.rect.x + self.reset_sprite.rect.width and \
    280. self.reset_sprite.rect.y <= y <= self.reset_sprite.rect.y + self.reset_sprite.rect.height:
    281. self.reset_sprite.color = Game_Info.PINK
    282. self.reset_sprite.update(self.reset_sprite.text)
    283. else:
    284. self.reset_sprite.color = Game_Info.BLUE
    285. self.reset_sprite.update(self.reset_sprite.text)
    286. # 鼠标点击事件
    287. elif event.type == pygame.MOUSEBUTTONDOWN:
    288. x, y = event.pos # 获取屏幕坐标位置
    289. # 点击游戏设置
    290. if self.__is_on_set(x, y):
    291. # 判断游戏是否暂停
    292. if not self.game_pause_flag:
    293. TypingGame.game_pause_flag = True
    294. # 游戏结束鼠标点击退出按钮
    295. if self.quit_sprite.rect.x <= x <= self.quit_sprite.rect.x + self.quit_sprite.rect.width and \
    296. self.quit_sprite.rect.y <= y <= self.quit_sprite.rect.y + self.quit_sprite.rect.height:
    297. pygame.quit()
    298. TypingGame.game_quit_flag = True
    299. sys.exit()
    300. # 游戏结束鼠标点击重玩按钮
    301. if self.reset_sprite.rect.x <= x <= self.reset_sprite.rect.x + self.reset_sprite.rect.width and \
    302. self.reset_sprite.rect.y <= y <= self.reset_sprite.rect.y + self.reset_sprite.rect.height:
    303. self.__reset_game()
    304. # 键盘事件
    305. elif event.type == pygame.KEYDOWN and not self.game_over_flag and not self.game_pause_flag:
    306. # 英文单引号的ASCII值是39、-是45、.是46
    307. # print(event.key)
    308. if (pygame.K_a <= event.key <= pygame.K_z) or event.key in (39, 45, 46):
    309. if self.spell_ok:
    310. # 如果单词拼写成功再按下键盘时清空内容
    311. self.word_content = ""
    312. self.spell_ok = False
    313. # 控制单词长度
    314. if len(self.word_content) < 40:
    315. # 记录键盘输入的字符
    316. self.word_content += pygame.key.name(event.key)
    317. else:
    318. print("Word to long")
    319. print(self.word_content)
    320. if event.key == pygame.K_BACKSPACE:
    321. self.__delete_words()
    322. elif event.type == pygame.KEYUP:
    323. self.backspace_count = 0
    324. # 实现长按backspace连续回删
    325. # 使用键盘提供的方法获取键盘按键 - 按键元组
    326. keys_pressed = pygame.key.get_pressed()
    327. # 判断元组中对应的按键索引值 1
    328. if keys_pressed[pygame.K_BACKSPACE]:
    329. self.backspace_count += 1
    330. if self.backspace_count > 20:
    331. self.__delete_words()
    332. def __is_on_set(self, x, y):
    333. """
    334. 检查是否在设置图片上
    335. :param x,y 鼠标的位置
    336. """
    337. img_set_x = self.game_set_sprite.rect.x
    338. img_set_y = self.game_set_sprite.rect.y
    339. img_set_w = self.game_set_sprite.rect.width
    340. img_set_h = self.game_set_sprite.rect.height
    341. if (img_set_x <= x <= img_set_x + img_set_w) and \
    342. (img_set_y <= y <= img_set_y + img_set_h):
    343. return True
    344. else:
    345. return False
    346. def __delete_words(self):
    347. """单词回删"""
    348. if self.word_content != "":
    349. self.word_content = self.word_content[:-1]
    350. print(self.word_content + "---" + str(len(self.word_content)))
    351. if self.spell_ok:
    352. # 如果单词拼写成功再按下键盘回删键时清空内容
    353. self.word_content = ""
    354. self.spell_ok = False
    355. def __random_generate_word(self, word_num=5):
    356. """
    357. 随机生成单词精灵
    358. :param word_num:精灵数量 默认5
    359. :return:
    360. """
    361. count = 0
    362. while len(self.word_group.sprites()) <= 30:
    363. index = random.randint(0, len(self.words) - 1)
    364. eng_word = self.words[index]["eng_word"]
    365. cn_comment = self.words[index]["cn_comment"]
    366. # print(eng_word + "----" + cn_comment)
    367. word_sprite = WordSprite(
    368. eng_word,
    369. cn_comment,
    370. speed=self.game_level_dict[int(self.game_conf.game_level)]['word_fall_speed'],
    371. size=int(self.game_conf.word_size),
    372. color=pygame.color.Color(str(self.game_conf.word_normal_color))
    373. )
    374. # 单词位置随机
    375. word_sprite.random_pos()
    376. # 检查新单词精灵是否与单词精灵组中的精灵碰撞(重叠)
    377. words = pygame.sprite.spritecollide(
    378. word_sprite, self.word_group, False,
    379. pygame.sprite.collide_circle_ratio(1)
    380. )
    381. # 碰撞(释放内存重新随机生成单词精灵)
    382. if len(words) > 0:
    383. word_sprite.kill()
    384. continue
    385. else:
    386. self.word_group.add(word_sprite)
    387. count += 1
    388. if count >= word_num:
    389. break
    390. def __game_over(self):
    391. """游戏结束"""
    392. self.game_score_sprite.hor_center(Game_Info.SCREEN_RECT)
    393. self.highest_sprite.hor_center(Game_Info.SCREEN_RECT)
    394. self.game_score_sprite.update(u"游戏分数: %s" % self.total_score)
    395. """
    396. history_score_dict
    397. {
    398. 'level_0': "{'score': None,'use_time': None,'create_time': None}",
    399. 'level_1': "{'score': None,'use_time': None,'create_time': None}",
    400. 'level_2': "{...}",
    401. ...
    402. }
    403. """
    404. # 显示历史最高
    405. highest_score_str = self.game_conf.history_score_dict['level_' + str(int(self.game_conf.game_level))]
    406. highest_score_dict = eval(highest_score_str)
    407. highest_score = highest_score_dict['score']
    408. if highest_score is None or int(self.total_score) > int(highest_score):
    409. # 更新历史记录
    410. highest_score = self.total_score
    411. highest_score_dict['score'] = str(self.total_score)
    412. highest_score_dict['use_time'] = str(self.use_time)[:5] + 's'
    413. highest_score_dict['create_time'] = str(time.strftime("%Y-%m-%d %H:%M"))
    414. self.game_conf.set_highest_score(str(highest_score_dict), 'level_' + str(int(self.game_conf.game_level)))
    415. else:
    416. highest_score = highest_score_dict['score']
    417. self.highest_sprite.update(u"历史最高: %s" % highest_score)
    418. def __check_spell_word(self):
    419. """检查拼写单词是否正确"""
    420. word_sprites = self.word_group.sprites()
    421. for word_sprite in word_sprites:
    422. # 判断单词内容是否相同
    423. if self.word_content.lower() == word_sprite.text.lower():
    424. # 判断血条是否超过总血条数
    425. if self.game_blood < self.game_total_blood:
    426. self.game_blood += 10
    427. self.total_score += 1
    428. self.spell_ok = True
    429. self.word_content = self.word_content + "\t" + str(word_sprite.cn_comment)
    430. word_sprite.kill()
    431. # 从预先创建完毕的动画中取出一个动画对象
    432. for animate in self.animates:
    433. if not animate.visible:
    434. # 设置动画位置
    435. animate.set_pos(word_sprite.rect.x, word_sprite.rect.y)
    436. # 动画对象状态设置为True
    437. animate.visible = True
    438. break
    439. def __draw_game_blood(self, color=Game_Info.GREEN):
    440. """绘制游戏能量"""
    441. if self.game_blood <= 3 * 10:
    442. color = Game_Info.RED
    443. if self.game_blood >= 25 * 10:
    444. color = Game_Info.BLUE
    445. if self.game_total_blood-30 <= self.game_blood <= self.game_total_blood:
    446. color = Game_Info.ORANGE
    447. # 绘制游戏能量
    448. pygame.draw.rect(
    449. self.screen, color,
    450. pygame.Rect(
    451. Game_Info.GAME_BLOOD_RECT.x + 2,
    452. Game_Info.GAME_BLOOD_RECT.y,
    453. self.game_blood,
    454. Game_Info.GAME_BLOOD_RECT.height
    455. )
    456. )
    457. pygame.draw.rect(self.screen, Game_Info.WHITE, Game_Info.GAME_BLOOD_RECT, 2)
    458. def __drop_blood(self):
    459. """持续掉血"""
    460. # if not self.game_pause_flag:
    461. # if int(self.use_time) > 0 and (int(self.use_time) / 6) % 2 == 0:
    462. # self.game_blood -= 0.5
    463. while not self.game_over_flag:
    464. if self.game_pause_flag:
    465. self.game_clock.tick(60)
    466. else:
    467. # 根据不同游戏等级掉血
    468. self.game_clock.tick(int(self.game_conf.game_level))
    469. self.game_blood -= 1
    470. def __animate_action(self):
    471. """开启单词拼写成功动画"""
    472. for animate in self.animates:
    473. if animate.visible:
    474. animate.action()
    475. def __reset_game(self):
    476. """游戏重玩"""
    477. del self # 释放内存
    478. pygame.quit()
    479. pygame.init()
    480. random_music()
    481. TypingGame.game_over_flag = False
    482. TypingGame.game_quit_flag = False
    483. TypingGame().start_game()
    484. def main():
    485. center_pos()
    486. # 启动游戏开始界面
    487. GameStartWin(title="Word Sprite").run()
    488. if __name__ == '__main__':
    489. main()

    2)游戏配置信息模块

    1. # !/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. import ctypes
    4. import pygame
    5. import configparser
    6. class GameConfig(object):
    7. """游戏配置文件类"""
    8. GAME_INFO = "game_info" # 配置文件游戏信息结点名称
    9. GAME_STYLE = "game_style" # 配置文件游戏样式结点名称
    10. GAME_SCORE = "game_score" # 配置文件游戏分数结点名称
    11. config_file_path = "resource/config.cfg" # 游戏配置文件路径
    12. # 把配置文件类设置成单例模式
    13. _instance = None
    14. def __new__(cls, *args, **kwargs):
    15. if cls._instance is None:
    16. cls._instance = super().__new__(cls)
    17. return cls._instance
    18. def __init__(self):
    19. self.author = None
    20. self.game_name = None
    21. self.version = None
    22. self.e_mail = None
    23. self.frame_pre_sec = None # 游戏帧率
    24. self.word_size = None # 英文单词的大小
    25. self.word_normal_color = None # 单词的正常颜色
    26. self.spell_ok_color = None # 单词拼写成功的颜色
    27. self.game_level = None # 游戏等级
    28. self.game_init_blood = None # 游戏初始血量
    29. self.history_score_dict = None # 游戏历史记录
    30. self.__parser_config()
    31. def __parser_config(self):
    32. """解析游戏配置文件"""
    33. self.conf_parser = configparser.ConfigParser()
    34. self.conf_parser.read(self.config_file_path, encoding='utf-8')
    35. # 游戏开发者信息
    36. self.author = self.conf_parser.get(self.GAME_INFO, 'author')
    37. self.game_name = self.conf_parser.get(self.GAME_INFO, 'game_name')
    38. self.version = self.conf_parser.get(self.GAME_INFO, 'version')
    39. self.e_mail = self.conf_parser.get(self.GAME_INFO, 'e-mail')
    40. # 游戏样式信息
    41. self.frame_pre_sec = self.conf_parser.get(self.GAME_STYLE, "frame_pre_sec")
    42. self.word_size = self.conf_parser.get(self.GAME_STYLE, "word_size")
    43. self.word_normal_color = self.conf_parser.get(self.GAME_STYLE, "word_normal_color")
    44. self.spell_ok_color = self.conf_parser.get(self.GAME_STYLE, "spell_ok_color")
    45. self.game_level = self.conf_parser.get(self.GAME_STYLE, "game_level")
    46. self.game_init_blood = self.conf_parser.get(self.GAME_STYLE, "game_init_blood")
    47. # {
    48. # 'level_0': "{'score': None,'use_time': None,'create_time': None}",
    49. # 'level_1': "{...}",
    50. # }
    51. # 历史最高信息
    52. self.history_score_dict = dict(self.conf_parser.items(self.GAME_SCORE))
    53. def set_word_size(self, word_size):
    54. """设置单词大小"""
    55. self.word_size = word_size
    56. self.conf_parser.set(self.GAME_STYLE, "word_size", str(word_size))
    57. self.conf_parser.write(open(self.config_file_path, mode='w'))
    58. def set_game_level(self, game_level):
    59. """设置游戏等级"""
    60. self.game_level = game_level
    61. self.conf_parser.set(self.GAME_STYLE, "game_level", str(game_level))
    62. self.conf_parser.write(open(self.config_file_path, mode='w'))
    63. def set_game_init_blood(self, game_init_blood):
    64. """设置游戏的初始血条"""
    65. self.game_init_blood = game_init_blood
    66. self.conf_parser.set(self.GAME_STYLE, "game_init_blood", str(game_init_blood))
    67. self.conf_parser.write(open(self.config_file_path, mode='w'))
    68. def set_word_normal_color(self, word_normal_color):
    69. """设置单词的正常颜色"""
    70. self.word_normal_color = word_normal_color
    71. self.conf_parser.set(self.GAME_STYLE, "word_normal_color", str(word_normal_color))
    72. self.conf_parser.write(open(self.config_file_path, mode='w'))
    73. def set_spell_ok_color(self, spell_ok_color):
    74. """设置单词拼写成功后的颜色"""
    75. self.spell_ok_color = spell_ok_color
    76. self.conf_parser.set(self.GAME_STYLE, "spell_ok_color", str(spell_ok_color))
    77. self.conf_parser.write(open(self.config_file_path, mode='w'))
    78. def set_highest_score(self, score_dict, game_level):
    79. """更新历史最高记录"""
    80. self.conf_parser.set(self.GAME_SCORE, str(game_level), str(score_dict))
    81. self.conf_parser.write(open(self.config_file_path, mode='w'))
    82. self.history_score_dict = dict(self.conf_parser.items(self.GAME_SCORE))
    83. # 获取系统屏幕分辨率(缩放比例后)
    84. win_api = ctypes.windll.user32
    85. SCREEN_X = win_api.GetSystemMetrics(0)
    86. SCREEN_Y = win_api.GetSystemMetrics(1)
    87. game_conf = GameConfig()
    88. GAME_MUSICS = ["resource/music/bgm1.mp3", "resource/music/bgm2.mp3"]
    89. GAME_NAME = game_conf.game_name
    90. GAME_LEVEL = {'1': 0.3, '2': 0.5, '3': 1, '4': 1.5, '5': 2} # 游戏困难等级与单词下落速度相互匹配字典
    91. SCREEN_RECT = pygame.Rect(0, 0, SCREEN_X * 0.85, SCREEN_Y * 0.85) # 游戏窗口大小(电脑分辨率 * 0.85)
    92. INPUT_RECT_WIDTH = 600
    93. INPUT_RECT_HEIGHT = 100
    94. GAME_BLOOD_RECT = pygame.Rect(SCREEN_RECT.width / 2 - 250, SCREEN_RECT.height - 26, 500, 25)
    95. GAME_ICON = "resource/image/rabbit.ico"
    96. GAME_ICON_32 = "resource/image/rabbit_32.png"
    97. GAME_ICON_48 = "resource/image/rabbit_48.png"
    98. VOICE_ICO = "resource/image/voice.png"
    99. MUTE_ICO = "resource/image/mute.png"
    100. GAME_BACKGROUND = "resource/image/game_bg.png"
    101. GAME_OVER_BACKGROUND = "resource/image/game_over.png"
    102. INPUT_BACKGROUND = "resource/image/input_bg.png"
    103. GAME_SET_BLUE = "resource/image/set_blue.png"
    104. GAME_SET_PINK = "resource/image/set_pink.png"
    105. GAME_FONT = "resource/font/HUI.TTF" # 游戏字体
    106. GAME_WORD_TEXT = "resource/en_word.txt" # 游戏单词文本
    107. # 单词拼写成功后的消失动画
    108. KILL_ANIMATION = ["resource/image/animation/" + str(img_num).zfill(3) + ".png" for img_num in range(8)]
    109. FRAME_PRE_SEC = int(game_conf.frame_pre_sec) # 游戏的刷新帧率
    110. WORD_SIZE = int(game_conf.word_size) # 单词大小
    111. WORD_FALL_SPEED = GAME_LEVEL[str(game_conf.game_level)] # 单词下落速度
    112. INIT_BLOOD = int(game_conf.game_init_blood) # 游戏初始血条
    113. # 创建单词的时间间隔(毫秒)
    114. CREATE_WORD_INTERVAL = 1000 * 5
    115. # 首次生成单词的数量
    116. GENERATE_WORD_NUM = 5
    117. # 游戏单词正常颜色和拼写颜色
    118. WORD_NORMAL_COLOR = str(game_conf.word_normal_color)
    119. SPELL_OK_COLOR = str(game_conf.spell_ok_color)
    120. WORD_COLOR = pygame.color.Color(WORD_NORMAL_COLOR)
    121. WORD_SPELL_OK_COLOR = pygame.color.Color(SPELL_OK_COLOR)
    122. # 字体颜色
    123. RED = pygame.color.Color("RED")
    124. YELLOW = pygame.color.Color("YELLOW")
    125. BLUE = pygame.color.Color("#70f3ff")
    126. GREEN = pygame.color.Color("GREEN")
    127. WHITE = pygame.color.Color("WHITE")
    128. ORANGE = pygame.color.Color("ORANGE")
    129. PINK = pygame.color.Color("#ff4777")
    130. # 创建单词事件
    131. CREATE_WORD_EVENT = pygame.USEREVENT
    132. # 游戏结束事件
    133. GAME_OVER_EVENT = pygame.USEREVENT + 1
    134. # 游戏音乐结束事件
    135. MUSIC_END_EVENT = pygame.USEREVENT + 2
    136. def main():
    137. game_conf1 = GameConfig()
    138. game_conf2 = GameConfig()
    139. game_conf1.word_size = 100
    140. game_conf2.game_init_blood = 50
    141. print(id(game_conf1))
    142. print(id(game_conf2))
    143. print(game_conf1.game_init_blood)
    144. print(game_conf2.word_size)
    145. socre_dict = game_conf.history_score_dict
    146. print(dict(socre_dict))
    147. print(eval(socre_dict['level_1']))
    148. print(GAME_BLOOD_RECT)
    149. # print(SCREEN_X, SCREEN_Y)
    150. # print(SCREEN_RECT)
    151. # print(SCREEN_RECT.size)
    152. # print(game_conf.frame_pre_sec)
    153. # print(game_conf.game_level)
    154. # print(game_conf.word_size)
    155. # print(game_conf.word_normal_color)
    156. # print(game_conf.spell_ok_color)
    157. # print(WORD_NORMAL_COLOR)
    158. # print(SPELL_OK_COLOR)
    159. # print(int(10.000000001))
    160. # print(SCREEN_X, SCREEN_Y)
    161. # print(SCREEN_RECT.size)
    162. if __name__ == '__main__':
    163. main()

    3)游戏视图模块

    1. import Game_Info
    2. import threading
    3. import PySimpleGUI as sg
    4. from Game_Info import GameConfig
    5. from tkinter import colorchooser
    6. from Game_Main import TypingGame
    7. class BaseWin(object):
    8. """窗口父类"""
    9. WIN_THEME = sg.theme('DarkBlue1')
    10. text_color = 'white'
    11. game_conf = GameConfig() # 游戏信息配置类
    12. def __init__(self, title):
    13. self.title = title
    14. self.window = None
    15. self.layout = list()
    16. def close_win(self):
    17. """关闭窗口"""
    18. if self.window is not None:
    19. self.window.close()
    20. class GameStartWin(BaseWin):
    21. """游戏开始窗口"""
    22. _voice_flag = True
    23. def __init__(self, title):
    24. super().__init__(title)
    25. self.__init_layout()
    26. def __init_layout(self):
    27. """初始化窗口布局"""
    28. if self._voice_flag:
    29. voice_img = Game_Info.VOICE_ICO
    30. else:
    31. voice_img = Game_Info.MUTE_ICO
    32. self.layout = [
    33. [sg.Text(size=(70, 0)), sg.Image(filename=voice_img, key='voice_control', enable_events=True)],
    34. [sg.Text(size=(10, 10)), sg.Text('Word Sprite', font=(u'宋体', 50)), sg.Text(size=(10, 10))],
    35. [sg.Text(size=(23, 10)), sg.Button(u'开始游戏', font=(u'宋体', 30), key='start_game'), sg.Text(size=(23, 10))],
    36. [sg.Text(size=(23, 5)), sg.Button(u'游戏设置', font=(u'宋体', 30), key='game_set'), sg.Text(size=(23, 5))],
    37. [sg.Text(size=(23, 10)), sg.Button(u'历史最高', font=(u'宋体', 30), key='show_score'), sg.Text(size=(23, 10))],
    38. [
    39. sg.Text(size=(70, 0)),
    40. sg.Image(
    41. filename=Game_Info.GAME_ICON_48,
    42. key='game_ico',
    43. enable_events=True
    44. )
    45. ]
    46. ]
    47. def run(self):
    48. """启动游戏开始窗口"""
    49. self.window = sg.Window(
    50. title=self.title,
    51. icon=Game_Info.GAME_ICON,
    52. layout=self.layout
    53. )
    54. self.__event_handler()
    55. def __event_handler(self):
    56. """窗口事件监听"""
    57. while True:
    58. event, value_dict = self.window.read(timeout=20)
    59. print(event, value_dict)
    60. # 静音控制
    61. if self._voice_flag:
    62. self.window.find_element('voice_control').update(filename=Game_Info.VOICE_ICO)
    63. else:
    64. self.window.find_element('voice_control').update(filename=Game_Info.MUTE_ICO)
    65. if event in (sg.WIN_CLOSED, 'Quit'):
    66. break
    67. elif event in 'voice_control':
    68. self.voice_control()
    69. elif event in 'game_ico':
    70. self.author_win()
    71. elif event in 'start_game':
    72. print('开始游戏')
    73. self.window.Hide()
    74. TypingGame.game_over_flag = False
    75. TypingGame.game_quit_flag = False
    76. threading.Thread(target=self.start_game).start() # 利用线程开启游戏防止窗口卡死
    77. elif event in 'game_set' or TypingGame.game_pause_flag:
    78. print('游戏设置')
    79. self.window.Disable()
    80. self.game_set()
    81. elif event in 'show_score':
    82. print('历史最高')
    83. self.window.Disable()
    84. self.show_score()
    85. elif TypingGame.game_quit_flag:
    86. self.window.UnHide()
    87. self.window.close()
    88. def voice_control(self):
    89. """游戏静音状态控制"""
    90. if self._voice_flag:
    91. GameStartWin._voice_flag = False
    92. self.window.find_element('voice_control').update(filename=Game_Info.MUTE_ICO)
    93. else:
    94. GameStartWin._voice_flag = True
    95. self.window.find_element('voice_control').update(filename=Game_Info.VOICE_ICO)
    96. def author_win(self):
    97. """游戏开发信息窗口"""
    98. self.window.Disable()
    99. game_conf = Game_Info.GameConfig()
    100. show_text = '游戏作者: \t' + game_conf.author + '\n\n'\
    101. '游戏名称: \t' + game_conf.game_name + '\n\n'\
    102. '游戏版本: \t' + game_conf.version + '\n\n'\
    103. '作者邮箱: \t' + game_conf.e_mail + '\n'
    104. sg.Popup(
    105. show_text,
    106. title=u'关于作者',
    107. icon=Game_Info.GAME_ICON,
    108. font=(u'宋体', 18),
    109. custom_text=(u' ★ ', u' ❤ '),
    110. button_color=('red', '#063288'),
    111. line_width=50,
    112. )
    113. self.window.Enable()
    114. def game_set(self):
    115. """游戏设置"""
    116. GameSetWin(u"游戏配置", self).run()
    117. def show_score(self):
    118. """查看历史最高分"""
    119. GameScoreWin(u'历史最高', self).run()
    120. @staticmethod
    121. def start_game():
    122. """开始游戏"""
    123. TypingGame().start_game()
    124. @classmethod
    125. def voice_flag(cls):
    126. return cls._voice_flag
    127. class GameExecuteWin(object):
    128. """游戏运行窗口"""
    129. pass
    130. class GameEndWin(object):
    131. """游戏结束窗口"""
    132. def __init__(self):
    133. pass
    134. class GameSetWin(BaseWin):
    135. """游戏配置信息窗口"""
    136. # 游戏等级对照字典
    137. game_level_dict = {
    138. 1: {"game_level_num": 5, "game_level_text": u"简单", "game_level_color": "green"},
    139. 2: {"game_level_num": 15, "game_level_text": u"上手", "game_level_color": "blue"},
    140. 3: {"game_level_num": 25, "game_level_text": u"中等", "game_level_color": "orange"},
    141. 4: {"game_level_num": 35, "game_level_text": u"困难", "game_level_color": "red"},
    142. 5: {"game_level_num": 50, "game_level_text": u"魔鬼", "game_level_color": "purple"}
    143. }
    144. def __init__(self, title, parent_win=None):
    145. """初始化游戏配置界面"""
    146. super().__init__(title)
    147. self.parent_win = parent_win
    148. self.word_normal_color = self.game_conf.word_normal_color
    149. self.spell_ok_color = self.game_conf.spell_ok_color
    150. self.__init_layout()
    151. def __init_layout(self):
    152. game_level_num = self.game_level_dict[int(self.game_conf.game_level)]["game_level_num"]
    153. game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["game_level_text"]
    154. game_level_color = self.game_level_dict[int(self.game_conf.game_level)]["game_level_color"]
    155. self.layout = [
    156. [
    157. sg.Text(u'游戏难度等级:', text_color=self.text_color),
    158. sg.Slider(
    159. range=(1, 50), default_value=game_level_num,
    160. size=(26, 18), orientation='h', key="game_level",
    161. enable_events=True, disable_number_display=True,
    162. ),
    163. sg.Button(
    164. game_level_text, key='game_level_btn',
    165. button_color=(self.text_color, game_level_color),
    166. ),
    167. ],
    168. [
    169. sg.Text(u'游戏字体大小:', text_color=self.text_color),
    170. sg.Slider(
    171. range=(15, 35), default_value=int(self.game_conf.word_size),
    172. size=(26, 18), enable_events=True,
    173. orientation='h', disable_number_display=True, key="word_size"
    174. ),
    175. sg.Text(
    176. str(self.game_conf.word_size), text_color=self.text_color, size=(3, 1),
    177. font=("宋体", int(self.game_conf.word_size)),
    178. key='word_size_num'
    179. ),
    180. ],
    181. [
    182. sg.Text(u'游戏初始血条:', text_color=self.text_color),
    183. sg.Slider(
    184. range=(5, 30), default_value=int(self.game_conf.game_init_blood),
    185. size=(26, 18), orientation='h',
    186. enable_events=True, disable_number_display=True, key='init_blood'
    187. ),
    188. sg.Text(
    189. str(self.game_conf.game_init_blood), size=(3, 1),
    190. text_color=self.text_color, key='blood_num'
    191. )
    192. ],
    193. [
    194. sg.Text(u'游戏静音状态:', text_color=self.text_color),
    195. sg.Radio(
    196. ' ', default=GameStartWin.voice_flag(), key='voice_open',
    197. group_id=1, text_color=self.text_color, enable_events=True
    198. ),
    199. sg.Image(filename=Game_Info.VOICE_ICO),
    200. sg.Text(' ' * 5),
    201. sg.Radio(
    202. ' ', default=not GameStartWin.voice_flag(), key='mute',
    203. group_id=1, text_color=self.text_color, enable_events=True
    204. ),
    205. sg.Image(filename=Game_Info.MUTE_ICO)
    206. ],
    207. [
    208. sg.Text(u'游戏字体颜色:', text_color=self.text_color),
    209. sg.Text(
    210. '', size=(17, 1),
    211. background_color=self.game_conf.word_normal_color,
    212. enable_events=True, key='word_normal_color'
    213. ),
    214. sg.Text(
    215. 'HUI', key='word_color_test',
    216. text_color=self.game_conf.word_normal_color,
    217. ),
    218. sg.Button(u'颜色选择', key='normal_ccb')
    219. ],
    220. [
    221. sg.Text(u'单词拼写颜色:', text_color=self.text_color),
    222. sg.Text(
    223. '', size=(17, 1),
    224. background_color=self.game_conf.spell_ok_color,
    225. enable_events=True, key='spell_ok_color'
    226. ),
    227. sg.Text(
    228. 'HUI', key='spell_color_test',
    229. text_color=self.game_conf.spell_ok_color,
    230. ),
    231. sg.Button(u'颜色选择', key='spell_ccb')
    232. ],
    233. [
    234. sg.Submit(u'暂时保存', key='temp_save', pad=((10, 350), (0, 0))),
    235. sg.Button(u'永久保存', key='permanent')
    236. ]
    237. ]
    238. def run(self):
    239. """开启游戏设置界面"""
    240. self.window = sg.Window(
    241. title=self.title,
    242. icon=Game_Info.GAME_ICON,
    243. layout=self.layout,
    244. font=("宋体", 18),
    245. element_padding=(10, 30),
    246. )
    247. # 开启事件监听
    248. self.__event_handler()
    249. @staticmethod
    250. def color_callback(color=None):
    251. """颜色按钮回调方法"""
    252. return colorchooser.askcolor(color)
    253. def __event_handler(self):
    254. while True:
    255. event, value_dict = self.window.read()
    256. # print(event, value_dict)
    257. if event in (None, 'Quit'):
    258. break
    259. elif event in ('voice_open', 'mute'):
    260. if value_dict['voice_open']:
    261. GameStartWin._voice_flag = True
    262. else:
    263. GameStartWin._voice_flag = False
    264. elif event in 'game_level':
    265. game_level = self.get_game_level(int(value_dict[event]))
    266. game_level_text = self.game_level_dict[game_level]['game_level_text']
    267. game_level_color = self.game_level_dict[game_level]['game_level_color']
    268. self.window.find_element('game_level_btn').update(
    269. game_level_text,
    270. button_color=(self.text_color, game_level_color)
    271. )
    272. elif event in 'game_level_btn':
    273. # 点击按钮切换游戏等级
    274. game_level = self.get_game_level(int(value_dict['game_level']))
    275. if game_level == 5:
    276. game_level = 0
    277. game_level_num = self.game_level_dict[game_level + 1]['game_level_num']
    278. game_level_text = self.game_level_dict[game_level + 1]['game_level_text']
    279. game_level_color = self.game_level_dict[game_level + 1]['game_level_color']
    280. self.window.find_element('game_level').update(game_level_num)
    281. self.window.find_element('game_level_btn').update(
    282. game_level_text,
    283. button_color=(self.text_color, game_level_color)
    284. )
    285. elif event in 'word_size':
    286. word_size_num = value_dict[event]
    287. self.window.find_element('word_size_num').update(int(word_size_num), font=(u'宋体', int(word_size_num)))
    288. elif event in 'init_blood':
    289. blood_num = int(value_dict[event])
    290. self.window.find_element('blood_num').update(str(blood_num))
    291. elif event in 'normal_ccb':
    292. # 游戏单词颜色选择
    293. self.window.Disable() # 让游戏配置窗口不可用,不让用户乱点击,防止多开
    294. choose_colors = self.color_callback(self.game_conf.word_normal_color)
    295. self.window.Enable() # 恢复游戏配置窗口
    296. if None not in choose_colors:
    297. self.window.find_element('word_normal_color').update(background_color=choose_colors[1])
    298. self.window.find_element('word_color_test').update(text_color=choose_colors[1])
    299. self.word_normal_color = choose_colors[1]
    300. elif event in 'spell_ccb':
    301. # 单词拼写颜色选择
    302. self.window.Disable() # 让游戏配置窗口不可用,不让用户乱点击,防止多开
    303. choose_colors = self.color_callback(self.game_conf.spell_ok_color)
    304. self.window.Enable() # 恢复游戏配置窗口
    305. if None not in choose_colors:
    306. self.window.find_element('spell_ok_color').update(background_color=choose_colors[1])
    307. self.window.find_element('spell_color_test').update(text_color=choose_colors[1])
    308. self.spell_ok_color = choose_colors[1]
    309. elif event in ('temp_save', 'permanent'):
    310. GameSetWin.SAVE_STATUS = True
    311. game_level = self.get_game_level(int(value_dict['game_level']))
    312. value_dict['game_level'] = game_level
    313. value_dict['normal_ccb'] = self.word_normal_color
    314. value_dict['spell_ccb'] = self.spell_ok_color
    315. if event in 'temp_save':
    316. self.temp_save(value_dict)
    317. elif event in 'permanent':
    318. self.permanent(value_dict)
    319. break
    320. self.window.close()
    321. TypingGame.game_pause_flag = False
    322. # 恢复父窗口可用
    323. if self.parent_win is not None:
    324. self.parent_win.window.Enable()
    325. def temp_save(self, game_dict):
    326. """临时保存游戏配置信息(临时有效,重开还原)"""
    327. """
    328. {
    329. 'game_level': 2,
    330. 'word_size': 26.0,
    331. 'init_blood': 20.0,
    332. 'voice_open': True,
    333. 'mute': False,
    334. 'normal_ccb': '#00ffff',
    335. 'spell_ccb': '#ff0000'
    336. }
    337. """
    338. self.game_conf.game_level = game_dict['game_level']
    339. self.game_conf.word_size = game_dict['word_size']
    340. self.game_conf.game_init_blood = game_dict['init_blood']
    341. self.game_conf.word_normal_color = game_dict['normal_ccb']
    342. self.game_conf.spell_ok_color = game_dict['spell_ccb']
    343. def permanent(self, game_dict):
    344. """永久保存游戏配置信息(写入配置文件)"""
    345. # 修改配置文件
    346. self.game_conf.set_game_level(game_dict['game_level'])
    347. self.game_conf.set_word_size(int(game_dict['word_size']))
    348. self.game_conf.set_game_init_blood(int(game_dict['init_blood']))
    349. self.game_conf.set_word_normal_color(game_dict['normal_ccb'])
    350. self.game_conf.set_spell_ok_color(game_dict['spell_ccb'])
    351. @staticmethod
    352. def get_game_level(data):
    353. game_level = 1
    354. if data <= 10:
    355. game_level = 1
    356. elif data <= 20:
    357. game_level = 2
    358. elif data <= 30:
    359. game_level = 3
    360. elif data <= 40:
    361. game_level = 4
    362. elif data <= 50:
    363. game_level = 5
    364. return game_level#
    365. class GameScoreWin(BaseWin):
    366. """游戏历史分数窗口"""
    367. heads = [
    368. '{:4}'.format(u'游戏等级'),
    369. '{:4}'.format(u'最高分'),
    370. '{:6}'.format(u'耗 时'),
    371. '{:4}'.format(u'创建时间'),
    372. ]
    373. levels = ['level_1', 'level_2', 'level_3', 'level_4', 'level_5']
    374. def __init__(self, title, parent_win=None):
    375. super().__init__(title)
    376. self.parent_win = parent_win
    377. self.__init_layout()
    378. def __init_layout(self):
    379. """初始化窗口布局"""
    380. score_dict = Game_Info.game_conf.history_score_dict # 游戏历史记录
    381. level_0, level_1 = eval(score_dict[self.levels[0]]), eval(score_dict[self.levels[1]])
    382. level_2, level_3 = eval(score_dict[self.levels[2]]), eval(score_dict[self.levels[3]])
    383. level_4 = eval(score_dict[self.levels[4]])
    384. header = [[sg.Text(h, pad=(31, 30)) for h in self.heads]]
    385. body = [
    386. [
    387. sg.Button(u'简单', button_color=('white', 'green')),
    388. sg.Text('{:4}'.format(str(level_0['score']))),
    389. sg.Text('{:6}'.format(str(level_0['use_time']))),
    390. sg.Text('{:4}'.format(str(level_0['create_time'])))
    391. ],
    392. [
    393. sg.Button(u'上手', button_color=('white', 'blue')),
    394. sg.Text('{:4}'.format(str(level_1['score']))),
    395. sg.Text('{:6}'.format(str(level_1['use_time']))),
    396. sg.Text('{:4}'.format(str(level_1['create_time'])))
    397. ],
    398. [
    399. sg.Button(u'中等', button_color=('white', 'orange')),
    400. sg.Text('{:4}'.format(str(level_2['score']))),
    401. sg.Text('{:6}'.format(str(level_2['use_time']))),
    402. sg.Text('{:4}'.format(str(level_2['create_time'])))
    403. ],
    404. [
    405. sg.Button(u'困难', button_color=('white', 'red')),
    406. sg.Text('{:4}'.format(str(level_3['score']))),
    407. sg.Text('{:6}'.format(str(level_3['use_time']))),
    408. sg.Text('{:4}'.format(str(level_3['create_time'])))
    409. ],
    410. [
    411. sg.Button(u'魔鬼', button_color=('white', 'purple')),
    412. sg.Text('{:4}'.format(str(level_4['score']))),
    413. sg.Text('{:6}'.format(str(level_4['use_time']))),
    414. sg.Text('{:4}'.format(str(level_4['create_time'])))
    415. ]
    416. ]
    417. self.layout = header + body
    418. def run(self):
    419. """启动游戏历史分数窗口"""
    420. self.window = sg.Window(
    421. title=self.title,
    422. icon=Game_Info.GAME_ICON,
    423. layout=self.layout,
    424. font=('宋体', 20),
    425. element_padding=(46, 30)
    426. )
    427. self.__event_handler()
    428. def __event_handler(self):
    429. """窗口事件监听"""
    430. while True:
    431. event, value_dict = self.window.read()
    432. print(event, value_dict)
    433. if event in (sg.WIN_CLOSED, 'Quit'):
    434. self.parent_win.window.Enable()
    435. break
    436. self.window.close()
    437. def main():
    438. GameStartWin(title="Word Sprite").run()
    439. if __name__ == '__main__':
    440. main()

    4)PyGame游戏精灵模块

    1. import pygame
    2. import random
    3. import Game_Info
    4. from Game_Info import GameConfig
    5. class BaseSprite(pygame.sprite.Sprite):
    6. """游戏精灵基类"""
    7. def __init__(self):
    8. super().__init__()
    9. self.image = None
    10. self.rect = None
    11. def set_pos(self, x, y):
    12. """设置精灵位置"""
    13. self.rect.x = x
    14. self.rect.y = y
    15. def hor_center(self, screen_rect):
    16. """
    17. 水平居中显示
    18. :param screen_rect: 游戏屏幕大小
    19. :return:
    20. """
    21. x = screen_rect.width / 2 - self.rect.width / 2
    22. self.set_pos(x, self.rect.y)
    23. class ImageSprite(BaseSprite):
    24. """图片精灵基类"""
    25. def __init__(self, image):
    26. super().__init__()
    27. self.image = pygame.image.load(image)
    28. self.rect = self.image.get_rect()
    29. def transform_scale(self, image, size: tuple):
    30. """缩放图片大小"""
    31. self.image = pygame.transform.scale(image, size)
    32. self.rect = self.image.get_rect()
    33. class TextSprite(BaseSprite):
    34. """文字精灵基类"""
    35. def __init__(self, text, size=Game_Info.WORD_SIZE, color=Game_Info.WHITE):
    36. super().__init__()
    37. self.text = text
    38. self.size = size
    39. self.color = color
    40. # 创建字体
    41. self.font = pygame.font.Font(Game_Info.GAME_FONT, self.size)
    42. # 根据字体创建显示对象(文字) render(self,text,antialias,color,background = None)
    43. self.image = self.font.render(text, True, self.color)
    44. self.rect = self.image.get_rect()
    45. def update(self, display_text):
    46. """更新显示的文字"""
    47. self.text = display_text
    48. rect_x = self.rect.x
    49. rect_y = self.rect.y
    50. self.image = self.font.render(self.text, True, self.color)
    51. self.rect = self.image.get_rect()
    52. self.rect.x = rect_x
    53. self.rect.y = rect_y
    54. class SpellSprite(TextSprite):
    55. """文字精灵基类"""
    56. def __init__(self, text, size=Game_Info.WORD_SIZE, color=Game_Info.WORD_SPELL_OK_COLOR):
    57. super().__init__(text, size, color)
    58. def update(self, display_text, color):
    59. """更新拼写的单词"""
    60. self.text = display_text
    61. self.color = color
    62. self.image = self.font.render(self.text, True, self.color)
    63. self.rect = self.image.get_rect()
    64. # 居中显示
    65. self.hor_center(Game_Info.SCREEN_RECT)
    66. self.set_pos(self.rect.x, 40)
    67. class WordSprite(TextSprite):
    68. """单词精灵类"""
    69. game_conf = GameConfig()
    70. def __init__(self, text, cn_comment, speed: float, size=28, color=Game_Info.WORD_COLOR):
    71. super().__init__(text, size, color)
    72. self.speed = speed # 单词下落的速度
    73. self.cn_comment = cn_comment # 英文单词的意思
    74. self.y = float(self.rect.y) # 用小数存储单词降落的位置(方可设置成小数)
    75. def random_pos(self):
    76. """随机位置"""
    77. word_x = random.randint(0, Game_Info.SCREEN_RECT.width - self.rect.width)
    78. word_y = random.randint(-50, 10)
    79. self.rect.x = word_x
    80. self.rect.y = word_y
    81. self.y = float(self.rect.y)
    82. def update(self, game):
    83. """更新单词精灵"""
    84. # 判断游戏是否暂停
    85. if game.game_pause_flag:
    86. self.speed = 0
    87. else:
    88. self.y += self.speed
    89. self.rect.y = self.y
    90. # 超出游戏屏幕,删除精灵
    91. if self.rect.y >= Game_Info.SCREEN_RECT.height:
    92. self.kill()
    93. # 根据不同游戏等级掉血
    94. game.game_blood -= int(self.game_conf.game_level) * 3
    95. # 游戏配置信息改变,更新单词
    96. self.size = int(self.game_conf.word_size)
    97. self.font = pygame.font.Font(Game_Info.GAME_FONT, self.size)
    98. self.speed = game.game_level_dict[int(self.game_conf.game_level)]['word_fall_speed']
    99. self.color = pygame.color.Color(self.game_conf.word_normal_color)
    100. # 游戏分数是10的倍数单词下落速度提升
    101. if game.total_score > 0 and game.total_score % 100 == 0:
    102. self.speed += 0.5
    103. # 游戏血条在[45 - 50]区间单词下落速度提升
    104. if 45 * 10 <= game.game_blood <= 50 * 10:
    105. self.speed += 1
    106. # 拼写的字母与单词匹配
    107. if len(str(game.word_content)) >= 1 and \
    108. str(game.word_content)[0].lower() in str(self.text)[0].lower() and \
    109. str(game.word_content).lower() in str(self.text).lower():
    110. self.color = pygame.color.Color(self.game_conf.spell_ok_color)
    111. # 更新单词颜色
    112. self.image = self.font.render(self.text, True, self.color)
    113. class Animation(object):
    114. """动画特效类"""
    115. def __init__(self, screen):
    116. """初始化动画资源"""
    117. self.main_screen = screen
    118. # 加载动画资源
    119. self.images = [pygame.image.load(img) for img in Game_Info.KILL_ANIMATION]
    120. # 设置当前动画播放索引
    121. self.index = 0
    122. # 动画播放间隔
    123. self.interval = 2
    124. self.interval_index = 0
    125. # 动画位置
    126. self.position = [0, 0]
    127. # 是否可见
    128. self.visible = False
    129. # 设置动画播放的位置
    130. def set_pos(self, x, y):
    131. self.position[0] = x
    132. self.position[1] = y
    133. # 动画播放
    134. def action(self):
    135. # 如果爆炸对象状态不可见,则不计算坐标
    136. if not self.visible:
    137. return
    138. # 控制每一帧图片的播放间隔
    139. self.interval_index += 1
    140. if self.interval_index < self.interval:
    141. return
    142. self.interval_index = 0
    143. self.index = self.index + 1
    144. if self.index >= len(self.images):
    145. self.index = 0
    146. self.visible = False
    147. # 绘制动画
    148. def draw(self):
    149. # 如果对象不可见,则不绘制
    150. if not self.visible:
    151. return
    152. self.main_screen.screen.blit(self.images[self.index], (self.position[0], self.position[1]))
    153. def main():
    154. pass
    155. if __name__ == '__main__':
    156. pass

    五、效果展示

    1)游戏界面

    ​2)游戏设置

    ​3)随机截图

    (打字开始掉下来各种单词,打完之后还会出现相应的单词中文解释)

    4)游戏结束

    (相应的时间打英文单词一个单词一分,又背景音乐的哦🎵)

    1. 你们要找的英语意思在这里
    2. 重誓
    3. 因为你没把重誓守住,
    4. 别的人成了我的朋友
    5. 但是每一次我面对死亡,
    6. 或者攀登梦想高处,
    7. 或心情振奋,喝了点酒,
    8. 突然间我总看见你脸庞.

    总结

    ​还有很多功能小编没有展示出来的啦~大家自己运行的时候可以一个一个看下子,嘿嘿~

    真的超级推荐这款游戏真的玩儿的时候音乐好听运行之后的界面也很好哦~

    科能是截图展示不了游戏本来的亚子,有点儿拉跨了,但是视频展示的话录制比较麻烦来着。

    (其实还是自己懒的弄视频的嘿嘿,勿怪勿怪)代码的哈找我记得撒👇

    老规矩,木子的文章汇总可以看到分类好的各种不同类型的文章,滴滴我大部分源码都在滴。

    🎯完整的免费源码领取处:找我吖!文末公众hao可自行领取,滴滴我也可!

    🔨推荐往期文章——

    项目4.7 电影订票选座系统

    【Python订票系统】这才是看电影选座的正确方法,原来我们都上当了~(选座位、一键购票)

    项目 3.9  码住雪景漫天飘雪小程序

    【Python码住雪景小程序】雪景人像最强攻略:让你一下美10倍、美醉了(中国人不骗中国人)

     项目 4.0 GIF制作神奇(斗罗大陆为例)

    【Python神器】推荐这款傻瓜式GIF制作工具,以后别再说不会了(好用到爆~)

    项目3.2  自动换壁纸

    【Python高级技能】超炫酷,电脑每天自动换壁纸,这个神器适合你。

    项目3.3  艺术字签名

    【艺术字签名生成器】】试卷家长签字居然被嫌弃了|“我觉得我还能再抢救一下,你看行嘛?“

    🎄文章汇总——

    汇总合集  Python—2022 |已有文章汇总 | 持续更新,直接看这篇就够了

    (更多内容+源码都在✨文章汇总哦!!欢迎阅读喜欢的文章🎉~)

  • 相关阅读:
    进程创建时自动打开的三个文件描述符
    跨时钟域(Clock Domain Crossing,CDC)
    第二十三章 使用任务管理器(一)
    flink 批处理和流式 wordcount
    A-LEVEL计算机科学得A*难吗?
    《面试八股文》之Zookeeper12卷
    企业微信服务商代开发应用验证CallBackUrl失败
    开发眼里的网络
    区分何时使用内连接或者外连接
    C语言,求一个整数的全部素数因子
  • 原文地址:https://blog.csdn.net/weixin_55822277/article/details/126311890