基于Python实现英语单词小游戏

Fawn ·
更新时间:2024-11-10
· 925 次阅读

目录

导语

一、敲代码之前的小tips

二、运行环境

三、素材(图片等)

四、代码展示

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

2)游戏配置信息模块

3)游戏视图模块

4)PyGame游戏精灵模块

五、效果展示

1)游戏界面

2)游戏设置

​3)随机截图

4)游戏结束

导语

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

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

一开始我抱着侥幸心理,心想上高中的时候英语不错,四级应该也很容易。不过成绩出来我就傻眼了,没有通过。然后我就制定了周密的学习计划,开始有计划地学习英语,等到第二次考试的时候终于通过啦。今天,小编给大家制作一款Python编程代码版本的四级考试打字小游戏,边玩儿游戏还能复习单词还能保持学习的积极性,这款代码游戏真的是考级姐妹的灵魂首先,让我们开正式康康叭

一、敲代码之前的小tips

仅个人观点勿喷

四级之前,大家要很认真的备考啦,每天做做各种类型的四级题,可以量不多,但是会用心的做,做完之后都会认真的总结,就算那种不仔细的原因也会写在错题旁边,借以提醒自己。每天这样去做的原因就是保持题感,毕竟四级是一门考试,好多题还是有很多套路的,但只要持之以恒地去联系,虽然套路深,铁杵磨成针。

听力方面:每次听完并对过答案之后会继续听那一份听力材料,因为第一次是泛听,只需要抓住关键词的信息成功get到答案就好,那么后面就要开始精听,这一次我们的目标就是听懂这个人到底在说什么,争取听懂每一句,好了,接下来,当我反复听一句话却怎么也听不懂其中的某几个词的时候,那我就找到可以收入宝囊的法器了,然后你就把这几个词好好地在牛津字典里查一查,记在自己的收集本上,还要多多巩固,因为这些词语出现在考试中,从某种程度上来说就属于高频词汇的。另外呢,在精听的时候,我们要多多注意朗读者说英语时的感觉,包括他的发音、语调,都很重要,所以也可以跟着他一起读英语,在边听边说的过程中,我们的耳朵对英语会更加地敏感。

阅读方面:在就应对四级考试的时候,刷题当然是不二选择,前面已经提到过四级套路深,所以考试之前,我每天大概会做一篇阅读,设定时间是很重要的,这样可以把握自己的考试节奏,不会太慌张。四级阅读题,一般都会按照文章的顺序来设计题目,一般情况下,四级阅读题的内容不会太少,信息量比较多,而我需要的又仅仅只是那几条有用的信息。那么,首先就先看文章后面的问题,带着问题去读文章,会起到事半功倍的效果,也节省时间。做完一篇阅读之后,需要认真总结错误原因,那么你错的题就错得很有意义,如果只是不停地做题,而不停下来反思原因,那做一万道题也不如做一道题。总结错误之后,同样需要仔细查阅陌生的单词,不断积累,方可在英语阅读中做到游刃有余。

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

在四级考试之前,会准备一个本子,认真写好每一篇作文或是翻译,字迹工整,仔细构思,写完以后和优秀范文对比,学习它的用法,在平时就养成好的习惯,到了考场上才会更加从容。我觉得,写得越多,就会写得越好,优美而实用的句型才会信手拈来。总之,这同样是个坚持的过程,但终究会破茧成蝶、妙笔生花的。

二、运行环境

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

境就可以了。

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

三、素材(图片等)

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

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

四、代码展示 1)主程序(英文打字小游戏主入口模块) # !/usr/bin/env python # -*- coding: utf-8 -*- """ Author: 顾木子吖 """ import os import sys import time import traceback import Game_View from Game_View import * from Game_Sprite import * def center_pos(): """设置游戏窗口相对电脑屏幕居中""" game_x = (Game_Info.SCREEN_X - Game_Info.SCREEN_RECT.width) / 2 game_y = (Game_Info.SCREEN_Y - Game_Info.SCREEN_RECT.height) / 2 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (game_x, game_y) def random_music(): """随机播放背景音乐""" # 判断是否是静音模式 print(Game_View.GameStartWin.voice_flag()) try: pygame.mixer.init() pygame.mixer.music.load(random.choice(Game_Info.GAME_MUSICS)) pygame.mixer.music.play(loops=0) except Exception as e: print("无法加载音频,请检查电脑配置" + str(e)) print(traceback.format_exc()) if not Game_View.GameStartWin.voice_flag(): pygame.mixer_music.set_volume(0) def parser_words() -> dict: """ 解析英语单词 :return {"eng_word": val, "cn_comment": val} """ english_words = [] word_contents = open(Game_Info.GAME_WORD_TEXT, encoding="gbk") for value in word_contents: value = value.lstrip() word_list = value.split(" ") words = [i for i in word_list if i != ''] if len(words) >= 2: # 把解析好的单词和注释封装到字典中,然后加入列表 english_words.append( {"eng_word": words[0], "cn_comment": words[1]}) return english_words class TypingGame(object): """打字游戏主类""" spell_ok = False # 用于标识单词拼写成功 game_pause_flag = False # 游戏暂停标志 game_over_flag = False # 游戏结束标志 game_quit_flag = False # 游戏退出标志 game_total_blood = Game_Info.GAME_BLOOD_RECT.width # 游戏总能量(血条) # 游戏等级对照字典 game_level_dict = { 1: {"word_fall_speed": 0.3, "level_text": u"简单", "level_color": "green"}, 2: {"word_fall_speed": 0.5, "level_text": u"上手", "level_color": "blue"}, 3: {"word_fall_speed": 1.0, "level_text": u"中等", "level_color": "orange"}, 4: {"word_fall_speed": 1.5, "level_text": u"困难", "level_color": "red"}, 5: {"word_fall_speed": 2.0, "level_text": u"魔鬼", "level_color": "purple"} } @staticmethod def game_init(): """游戏初始化""" # 初始化游戏字体 pygame.font.init() # 设置游戏标题和图标 pygame.display.set_caption(Game_Info.GAME_NAME) pygame.display.set_icon(pygame.image.load(Game_Info.GAME_ICON_32)) @staticmethod def set_game_event(): """设置游戏事件""" # 设置创建单词的定时器 pygame.time.set_timer(Game_Info.CREATE_WORD_EVENT, Game_Info.CREATE_WORD_INTERVAL) # 设置游戏音乐结束事件 try: pygame.mixer.music.set_endevent(Game_Info.MUSIC_END_EVENT) except Exception as e: print("无法设置音乐结束事件\t" + str(e)) print(traceback.format_exc()) def __init__(self): self.words = parser_words() self.game_conf = GameConfig() # 游戏配置信息 self.game_default_voice = 20 # 游戏默认音量 self.use_time = 0 # 记录游戏使用的时间 self.total_score = 0 # 记录游戏拼写成功了多少个单词 self.word_content = "" # 键盘输入的单词 self.backspace_count = 0 # 回删键按下的次数 # 预先创建动画对象 self.animates = [Animation(self) for _ in range(5)] # 游戏初始血条值 self.game_blood = int(self.game_conf.game_init_blood) * 10 self.game_clock = pygame.time.Clock() self.screen = pygame.display.set_mode(Game_Info.SCREEN_RECT.size) self.game_init() self.set_game_event() # 设置游戏事件 self.__create_sprite() # 创建游戏精灵 def __create_sprite(self): """创建精灵和精灵组""" # 背景精灵 back_sprite = ImageSprite(Game_Info.GAME_BACKGROUND) # 根据游戏屏幕的大小适配背景图(可能会导致背景图变形) back_sprite.transform_scale( back_sprite.image, (Game_Info.SCREEN_RECT.width, Game_Info.SCREEN_RECT.height) ) self.back_group = pygame.sprite.Group(back_sprite) # 英文单词显示框 input_rect_sprite = ImageSprite(Game_Info.INPUT_BACKGROUND) # 缩放图片 input_rect_sprite.transform_scale( input_rect_sprite.image, (Game_Info.INPUT_RECT_WIDTH, Game_Info.INPUT_RECT_HEIGHT) ) # 水平居中显示 input_rect_sprite.hor_center(Game_Info.SCREEN_RECT) self.input_rect_group = pygame.sprite.Group(input_rect_sprite) # 创建“游戏设置”图片 self.game_set_sprite = ImageSprite(Game_Info.GAME_SET_PINK) set_x = Game_Info.SCREEN_RECT.width - self.game_set_sprite.rect.width - 10 set_y = Game_Info.SCREEN_RECT.height - self.game_set_sprite.rect.height - 10 self.game_set_sprite.set_pos(set_x, set_y) self.game_set_sprite_group = pygame.sprite.Group(self.game_set_sprite) # 拼写的单词 spell_word_sprite = SpellSprite( "", size=26, color=pygame.color.Color(self.game_conf.spell_ok_color) ) spell_word_sprite.hor_center(Game_Info.SCREEN_RECT) spell_word_sprite.set_pos(spell_word_sprite.rect.x, 40) self.spell_word_group = pygame.sprite.Group(spell_word_sprite) # 创建单词精灵组 self.word_group = pygame.sprite.Group() self.__random_generate_word(Game_Info.GENERATE_WORD_NUM) # 创建显示游戏时间精灵 time_sprite = TextSprite(text="Time: 0", size=28, color=Game_Info.BLUE) time_sprite.set_pos(5, 0) self.time_group = pygame.sprite.Group(time_sprite) # 游戏分数 self.score_sprite = TextSprite("Score: 0", size=30, color=Game_Info.BLUE) self.score_sprite.set_pos(Game_Info.SCREEN_RECT.width - self.score_sprite.rect.width - 20, 3) self.score_group = pygame.sprite.Group(self.score_sprite) # 游戏结束精灵(组) self.__game_over_sprite() def __game_over_sprite(self): """创建游戏结束的精灵(组)""" self.game_over_group = pygame.sprite.Group() game_over_sprite = TextSprite("Game Over", 100, Game_Info.BLUE) game_over_sprite.rect.y = (Game_Info.SCREEN_RECT.height - game_over_sprite.rect.height - 400) / 2 game_over_sprite.hor_center(Game_Info.SCREEN_RECT) game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["level_text"] game_level_color = pygame.color.Color(self.game_level_dict[int(self.game_conf.game_level)]["level_color"]) self.game_level_sprite = TextSprite(u"游戏等级: " + game_level_text, 50, game_level_color) self.game_level_sprite.rect.y = game_over_sprite.rect.y + 100 + 50 self.game_level_sprite.hor_center(Game_Info.SCREEN_RECT) self.game_score_sprite = TextSprite(u"游戏分数: ", 50, Game_Info.BLUE) self.game_score_sprite.rect.y = game_over_sprite.rect.y + 200 + 50 self.game_score_sprite.hor_center(Game_Info.SCREEN_RECT) self.highest_sprite = TextSprite(u"历史最高: ", 50, Game_Info.BLUE) self.highest_sprite.rect.y = game_over_sprite.rect.y + 300 + 50 self.highest_sprite.hor_center(Game_Info.SCREEN_RECT) self.quit_sprite = TextSprite(u"退出", 50, Game_Info.BLUE) self.quit_sprite.set_pos( game_over_sprite.rect.x - self.quit_sprite.rect.width, game_over_sprite.rect.y + 400 + 10 ) self.reset_sprite = TextSprite(u"重 玩", 50, Game_Info.BLUE) self.reset_sprite.set_pos( game_over_sprite.rect.x + game_over_sprite.rect.width, game_over_sprite.rect.y + 400 + 10 ) self.game_over_group.add( game_over_sprite, self.game_level_sprite, self.game_score_sprite, self.highest_sprite, self.quit_sprite, self.reset_sprite ) def __update_sprite(self): """更新精灵""" self.back_group.update() self.back_group.draw(self.screen) self.game_set_sprite_group.update() self.game_set_sprite_group.draw(self.screen) self.input_rect_group.update() self.input_rect_group.draw(self.screen) # 计算游戏使用时间 if not self.game_pause_flag and not self.game_over_flag: self.use_time += 0.1 display_time = "Time: " + str(self.use_time / 6) self.time_group.update(display_time[:12]) self.time_group.draw(self.screen) self.score_sprite.set_pos(Game_Info.SCREEN_RECT.width - self.score_sprite.rect.width - 20, 3) self.score_group.update("Score: " + str(self.total_score)) self.score_group.draw(self.screen) # 判断是否游戏结束 if self.game_over_flag: self.__game_over() game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["level_text"] self.game_level_sprite.update("游戏等级: " + str(game_level_text)) self.game_over_group.draw(self.screen) else: if not self.game_pause_flag: self.word_group.update(self) self.word_group.draw(self.screen) spell_ok_color = pygame.Color(self.game_conf.spell_ok_color) self.spell_word_group.update(self.word_content, spell_ok_color) self.spell_word_group.draw(self.screen) # 更新游戏能量条 if 0 <= self.game_blood <= self.game_total_blood: self.__draw_game_blood() # 单词精灵拼写成功动画 for animate in self.animates: if animate.visible: animate.draw() def start_game(self): """打字游戏开启""" # 随机播放背景音乐 random_music() # 利用多线程完成游戏持续掉血 drop_blood_t = threading.Thread(target=self.__drop_blood) drop_blood_t.start() while True: # 是否设置成静音 if not Game_View.GameStartWin.voice_flag(): pygame.mixer_music.set_volume(0) else: pygame.mixer_music.set_volume(self.game_default_voice) # 设置游戏刷新帧率 self.game_clock.tick(Game_Info.FRAME_PRE_SEC) # 判断游戏结束 if self.game_blood < 0: TypingGame.game_over_flag = True else: self.__animate_action() self.__check_spell_word() self.__update_sprite() self.__event_handle() pygame.display.update() def __event_handle(self): """游戏事件监听""" # 遍历所有事件 for event in pygame.event.get(): try: if pygame.mixer.music.get_endevent() == Game_Info.MUSIC_END_EVENT and \ not pygame.mixer.music.get_busy(): # 如果music播放结束且没有音乐在播放就随机下一首 print("下一首") random_music() except: pass # 如果单击关闭窗口,则退出 if event.type == pygame.QUIT and not self.game_pause_flag: pygame.quit() TypingGame.game_quit_flag = True sys.exit() # 创建单词事件 elif event.type == Game_Info.CREATE_WORD_EVENT: if not self.game_over_flag and not self.game_pause_flag: # 游戏结束或者暂停就停止生成单词了 self.__random_generate_word(word_num=3) # 鼠标移动事件 elif event.type == pygame.MOUSEMOTION: x, y = event.pos # 获取屏幕坐标位置 if self.__is_on_set(x, y): self.game_set_sprite.image = pygame.image.load(Game_Info.GAME_SET_BLUE) else: self.game_set_sprite.image = pygame.image.load(Game_Info.GAME_SET_PINK) # 游戏结束鼠标悬浮在确定按钮上变色 if self.quit_sprite.rect.x <= x <= self.quit_sprite.rect.x + self.quit_sprite.rect.width and \ self.quit_sprite.rect.y <= y <= self.quit_sprite.rect.y + self.quit_sprite.rect.height: self.quit_sprite.color = Game_Info.PINK self.quit_sprite.update(self.quit_sprite.text) else: self.quit_sprite.color = Game_Info.BLUE self.quit_sprite.update(self.quit_sprite.text) # 游戏结束鼠标悬浮在重玩按钮上变色 if self.reset_sprite.rect.x <= x <= self.reset_sprite.rect.x + self.reset_sprite.rect.width and \ self.reset_sprite.rect.y <= y <= self.reset_sprite.rect.y + self.reset_sprite.rect.height: self.reset_sprite.color = Game_Info.PINK self.reset_sprite.update(self.reset_sprite.text) else: self.reset_sprite.color = Game_Info.BLUE self.reset_sprite.update(self.reset_sprite.text) # 鼠标点击事件 elif event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos # 获取屏幕坐标位置 # 点击游戏设置 if self.__is_on_set(x, y): # 判断游戏是否暂停 if not self.game_pause_flag: TypingGame.game_pause_flag = True # 游戏结束鼠标点击退出按钮 if self.quit_sprite.rect.x <= x <= self.quit_sprite.rect.x + self.quit_sprite.rect.width and \ self.quit_sprite.rect.y <= y <= self.quit_sprite.rect.y + self.quit_sprite.rect.height: pygame.quit() TypingGame.game_quit_flag = True sys.exit() # 游戏结束鼠标点击重玩按钮 if self.reset_sprite.rect.x <= x <= self.reset_sprite.rect.x + self.reset_sprite.rect.width and \ self.reset_sprite.rect.y <= y <= self.reset_sprite.rect.y + self.reset_sprite.rect.height: self.__reset_game() # 键盘事件 elif event.type == pygame.KEYDOWN and not self.game_over_flag and not self.game_pause_flag: # 英文单引号的ASCII值是39、-是45、.是46 # print(event.key) if (pygame.K_a <= event.key <= pygame.K_z) or event.key in (39, 45, 46): if self.spell_ok: # 如果单词拼写成功再按下键盘时清空内容 self.word_content = "" self.spell_ok = False # 控制单词长度 if len(self.word_content) < 40: # 记录键盘输入的字符 self.word_content += pygame.key.name(event.key) else: print("Word to long") print(self.word_content) if event.key == pygame.K_BACKSPACE: self.__delete_words() elif event.type == pygame.KEYUP: self.backspace_count = 0 # 实现长按backspace连续回删 # 使用键盘提供的方法获取键盘按键 - 按键元组 keys_pressed = pygame.key.get_pressed() # 判断元组中对应的按键索引值 1 if keys_pressed[pygame.K_BACKSPACE]: self.backspace_count += 1 if self.backspace_count > 20: self.__delete_words() def __is_on_set(self, x, y): """ 检查是否在设置图片上 :param x,y 鼠标的位置 """ img_set_x = self.game_set_sprite.rect.x img_set_y = self.game_set_sprite.rect.y img_set_w = self.game_set_sprite.rect.width img_set_h = self.game_set_sprite.rect.height if (img_set_x <= x <= img_set_x + img_set_w) and \ (img_set_y <= y <= img_set_y + img_set_h): return True else: return False def __delete_words(self): """单词回删""" if self.word_content != "": self.word_content = self.word_content[:-1] print(self.word_content + "---" + str(len(self.word_content))) if self.spell_ok: # 如果单词拼写成功再按下键盘回删键时清空内容 self.word_content = "" self.spell_ok = False def __random_generate_word(self, word_num=5): """ 随机生成单词精灵 :param word_num:精灵数量 默认5 :return: """ count = 0 while len(self.word_group.sprites()) <= 30: index = random.randint(0, len(self.words) - 1) eng_word = self.words[index]["eng_word"] cn_comment = self.words[index]["cn_comment"] # print(eng_word + "----" + cn_comment) word_sprite = WordSprite( eng_word, cn_comment, speed=self.game_level_dict[int(self.game_conf.game_level)]['word_fall_speed'], size=int(self.game_conf.word_size), color=pygame.color.Color(str(self.game_conf.word_normal_color)) ) # 单词位置随机 word_sprite.random_pos() # 检查新单词精灵是否与单词精灵组中的精灵碰撞(重叠) words = pygame.sprite.spritecollide( word_sprite, self.word_group, False, pygame.sprite.collide_circle_ratio(1) ) # 碰撞(释放内存重新随机生成单词精灵) if len(words) > 0: word_sprite.kill() continue else: self.word_group.add(word_sprite) count += 1 if count >= word_num: break def __game_over(self): """游戏结束""" self.game_score_sprite.hor_center(Game_Info.SCREEN_RECT) self.highest_sprite.hor_center(Game_Info.SCREEN_RECT) self.game_score_sprite.update(u"游戏分数: %s" % self.total_score) """ history_score_dict { 'level_0': "{'score': None,'use_time': None,'create_time': None}", 'level_1': "{'score': None,'use_time': None,'create_time': None}", 'level_2': "{...}", ... } """ # 显示历史最高 highest_score_str = self.game_conf.history_score_dict['level_' + str(int(self.game_conf.game_level))] highest_score_dict = eval(highest_score_str) highest_score = highest_score_dict['score'] if highest_score is None or int(self.total_score) > int(highest_score): # 更新历史记录 highest_score = self.total_score highest_score_dict['score'] = str(self.total_score) highest_score_dict['use_time'] = str(self.use_time)[:5] + 's' highest_score_dict['create_time'] = str(time.strftime("%Y-%m-%d %H:%M")) self.game_conf.set_highest_score(str(highest_score_dict), 'level_' + str(int(self.game_conf.game_level))) else: highest_score = highest_score_dict['score'] self.highest_sprite.update(u"历史最高: %s" % highest_score) def __check_spell_word(self): """检查拼写单词是否正确""" word_sprites = self.word_group.sprites() for word_sprite in word_sprites: # 判断单词内容是否相同 if self.word_content.lower() == word_sprite.text.lower(): # 判断血条是否超过总血条数 if self.game_blood < self.game_total_blood: self.game_blood += 10 self.total_score += 1 self.spell_ok = True self.word_content = self.word_content + "\t" + str(word_sprite.cn_comment) word_sprite.kill() # 从预先创建完毕的动画中取出一个动画对象 for animate in self.animates: if not animate.visible: # 设置动画位置 animate.set_pos(word_sprite.rect.x, word_sprite.rect.y) # 动画对象状态设置为True animate.visible = True break def __draw_game_blood(self, color=Game_Info.GREEN): """绘制游戏能量""" if self.game_blood <= 3 * 10: color = Game_Info.RED if self.game_blood >= 25 * 10: color = Game_Info.BLUE if self.game_total_blood-30 <= self.game_blood <= self.game_total_blood: color = Game_Info.ORANGE # 绘制游戏能量 pygame.draw.rect( self.screen, color, pygame.Rect( Game_Info.GAME_BLOOD_RECT.x + 2, Game_Info.GAME_BLOOD_RECT.y, self.game_blood, Game_Info.GAME_BLOOD_RECT.height ) ) pygame.draw.rect(self.screen, Game_Info.WHITE, Game_Info.GAME_BLOOD_RECT, 2) def __drop_blood(self): """持续掉血""" # if not self.game_pause_flag: # if int(self.use_time) > 0 and (int(self.use_time) / 6) % 2 == 0: # self.game_blood -= 0.5 while not self.game_over_flag: if self.game_pause_flag: self.game_clock.tick(60) else: # 根据不同游戏等级掉血 self.game_clock.tick(int(self.game_conf.game_level)) self.game_blood -= 1 def __animate_action(self): """开启单词拼写成功动画""" for animate in self.animates: if animate.visible: animate.action() def __reset_game(self): """游戏重玩""" del self # 释放内存 pygame.quit() pygame.init() random_music() TypingGame.game_over_flag = False TypingGame.game_quit_flag = False TypingGame().start_game() def main(): center_pos() # 启动游戏开始界面 GameStartWin(title="Word Sprite").run() if __name__ == '__main__': main() 2)游戏配置信息模块 # !/usr/bin/env python # -*- coding: utf-8 -*- import ctypes import pygame import configparser class GameConfig(object): """游戏配置文件类""" GAME_INFO = "game_info" # 配置文件游戏信息结点名称 GAME_STYLE = "game_style" # 配置文件游戏样式结点名称 GAME_SCORE = "game_score" # 配置文件游戏分数结点名称 config_file_path = "resource/config.cfg" # 游戏配置文件路径 # 把配置文件类设置成单例模式 _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): self.author = None self.game_name = None self.version = None self.e_mail = None self.frame_pre_sec = None # 游戏帧率 self.word_size = None # 英文单词的大小 self.word_normal_color = None # 单词的正常颜色 self.spell_ok_color = None # 单词拼写成功的颜色 self.game_level = None # 游戏等级 self.game_init_blood = None # 游戏初始血量 self.history_score_dict = None # 游戏历史记录 self.__parser_config() def __parser_config(self): """解析游戏配置文件""" self.conf_parser = configparser.ConfigParser() self.conf_parser.read(self.config_file_path, encoding='utf-8') # 游戏开发者信息 self.author = self.conf_parser.get(self.GAME_INFO, 'author') self.game_name = self.conf_parser.get(self.GAME_INFO, 'game_name') self.version = self.conf_parser.get(self.GAME_INFO, 'version') self.e_mail = self.conf_parser.get(self.GAME_INFO, 'e-mail') # 游戏样式信息 self.frame_pre_sec = self.conf_parser.get(self.GAME_STYLE, "frame_pre_sec") self.word_size = self.conf_parser.get(self.GAME_STYLE, "word_size") self.word_normal_color = self.conf_parser.get(self.GAME_STYLE, "word_normal_color") self.spell_ok_color = self.conf_parser.get(self.GAME_STYLE, "spell_ok_color") self.game_level = self.conf_parser.get(self.GAME_STYLE, "game_level") self.game_init_blood = self.conf_parser.get(self.GAME_STYLE, "game_init_blood") # { # 'level_0': "{'score': None,'use_time': None,'create_time': None}", # 'level_1': "{...}", # } # 历史最高信息 self.history_score_dict = dict(self.conf_parser.items(self.GAME_SCORE)) def set_word_size(self, word_size): """设置单词大小""" self.word_size = word_size self.conf_parser.set(self.GAME_STYLE, "word_size", str(word_size)) self.conf_parser.write(open(self.config_file_path, mode='w')) def set_game_level(self, game_level): """设置游戏等级""" self.game_level = game_level self.conf_parser.set(self.GAME_STYLE, "game_level", str(game_level)) self.conf_parser.write(open(self.config_file_path, mode='w')) def set_game_init_blood(self, game_init_blood): """设置游戏的初始血条""" self.game_init_blood = game_init_blood self.conf_parser.set(self.GAME_STYLE, "game_init_blood", str(game_init_blood)) self.conf_parser.write(open(self.config_file_path, mode='w')) def set_word_normal_color(self, word_normal_color): """设置单词的正常颜色""" self.word_normal_color = word_normal_color self.conf_parser.set(self.GAME_STYLE, "word_normal_color", str(word_normal_color)) self.conf_parser.write(open(self.config_file_path, mode='w')) def set_spell_ok_color(self, spell_ok_color): """设置单词拼写成功后的颜色""" self.spell_ok_color = spell_ok_color self.conf_parser.set(self.GAME_STYLE, "spell_ok_color", str(spell_ok_color)) self.conf_parser.write(open(self.config_file_path, mode='w')) def set_highest_score(self, score_dict, game_level): """更新历史最高记录""" self.conf_parser.set(self.GAME_SCORE, str(game_level), str(score_dict)) self.conf_parser.write(open(self.config_file_path, mode='w')) self.history_score_dict = dict(self.conf_parser.items(self.GAME_SCORE)) # 获取系统屏幕分辨率(缩放比例后) win_api = ctypes.windll.user32 SCREEN_X = win_api.GetSystemMetrics(0) SCREEN_Y = win_api.GetSystemMetrics(1) game_conf = GameConfig() GAME_MUSICS = ["resource/music/bgm1.mp3", "resource/music/bgm2.mp3"] GAME_NAME = game_conf.game_name GAME_LEVEL = {'1': 0.3, '2': 0.5, '3': 1, '4': 1.5, '5': 2} # 游戏困难等级与单词下落速度相互匹配字典 SCREEN_RECT = pygame.Rect(0, 0, SCREEN_X * 0.85, SCREEN_Y * 0.85) # 游戏窗口大小(电脑分辨率 * 0.85) INPUT_RECT_WIDTH = 600 INPUT_RECT_HEIGHT = 100 GAME_BLOOD_RECT = pygame.Rect(SCREEN_RECT.width / 2 - 250, SCREEN_RECT.height - 26, 500, 25) GAME_ICON = "resource/image/rabbit.ico" GAME_ICON_32 = "resource/image/rabbit_32.png" GAME_ICON_48 = "resource/image/rabbit_48.png" VOICE_ICO = "resource/image/voice.png" MUTE_ICO = "resource/image/mute.png" GAME_BACKGROUND = "resource/image/game_bg.png" GAME_OVER_BACKGROUND = "resource/image/game_over.png" INPUT_BACKGROUND = "resource/image/input_bg.png" GAME_SET_BLUE = "resource/image/set_blue.png" GAME_SET_PINK = "resource/image/set_pink.png" GAME_FONT = "resource/font/HUI.TTF" # 游戏字体 GAME_WORD_TEXT = "resource/en_word.txt" # 游戏单词文本 # 单词拼写成功后的消失动画 KILL_ANIMATION = ["resource/image/animation/" + str(img_num).zfill(3) + ".png" for img_num in range(8)] FRAME_PRE_SEC = int(game_conf.frame_pre_sec) # 游戏的刷新帧率 WORD_SIZE = int(game_conf.word_size) # 单词大小 WORD_FALL_SPEED = GAME_LEVEL[str(game_conf.game_level)] # 单词下落速度 INIT_BLOOD = int(game_conf.game_init_blood) # 游戏初始血条 # 创建单词的时间间隔(毫秒) CREATE_WORD_INTERVAL = 1000 * 5 # 首次生成单词的数量 GENERATE_WORD_NUM = 5 # 游戏单词正常颜色和拼写颜色 WORD_NORMAL_COLOR = str(game_conf.word_normal_color) SPELL_OK_COLOR = str(game_conf.spell_ok_color) WORD_COLOR = pygame.color.Color(WORD_NORMAL_COLOR) WORD_SPELL_OK_COLOR = pygame.color.Color(SPELL_OK_COLOR) # 字体颜色 RED = pygame.color.Color("RED") YELLOW = pygame.color.Color("YELLOW") BLUE = pygame.color.Color("#70f3ff") GREEN = pygame.color.Color("GREEN") WHITE = pygame.color.Color("WHITE") ORANGE = pygame.color.Color("ORANGE") PINK = pygame.color.Color("#ff4777") # 创建单词事件 CREATE_WORD_EVENT = pygame.USEREVENT # 游戏结束事件 GAME_OVER_EVENT = pygame.USEREVENT + 1 # 游戏音乐结束事件 MUSIC_END_EVENT = pygame.USEREVENT + 2 def main(): game_conf1 = GameConfig() game_conf2 = GameConfig() game_conf1.word_size = 100 game_conf2.game_init_blood = 50 print(id(game_conf1)) print(id(game_conf2)) print(game_conf1.game_init_blood) print(game_conf2.word_size) socre_dict = game_conf.history_score_dict print(dict(socre_dict)) print(eval(socre_dict['level_1'])) print(GAME_BLOOD_RECT) # print(SCREEN_X, SCREEN_Y) # print(SCREEN_RECT) # print(SCREEN_RECT.size) # print(game_conf.frame_pre_sec) # print(game_conf.game_level) # print(game_conf.word_size) # print(game_conf.word_normal_color) # print(game_conf.spell_ok_color) # print(WORD_NORMAL_COLOR) # print(SPELL_OK_COLOR) # print(int(10.000000001)) # print(SCREEN_X, SCREEN_Y) # print(SCREEN_RECT.size) if __name__ == '__main__': main() 3)游戏视图模块 import Game_Info import threading import PySimpleGUI as sg from Game_Info import GameConfig from tkinter import colorchooser from Game_Main import TypingGame class BaseWin(object): """窗口父类""" WIN_THEME = sg.theme('DarkBlue1') text_color = 'white' game_conf = GameConfig() # 游戏信息配置类 def __init__(self, title): self.title = title self.window = None self.layout = list() def close_win(self): """关闭窗口""" if self.window is not None: self.window.close() class GameStartWin(BaseWin): """游戏开始窗口""" _voice_flag = True def __init__(self, title): super().__init__(title) self.__init_layout() def __init_layout(self): """初始化窗口布局""" if self._voice_flag: voice_img = Game_Info.VOICE_ICO else: voice_img = Game_Info.MUTE_ICO self.layout = [ [sg.Text(size=(70, 0)), sg.Image(filename=voice_img, key='voice_control', enable_events=True)], [sg.Text(size=(10, 10)), sg.Text('Word Sprite', font=(u'宋体', 50)), sg.Text(size=(10, 10))], [sg.Text(size=(23, 10)), sg.Button(u'开始游戏', font=(u'宋体', 30), key='start_game'), sg.Text(size=(23, 10))], [sg.Text(size=(23, 5)), sg.Button(u'游戏设置', font=(u'宋体', 30), key='game_set'), sg.Text(size=(23, 5))], [sg.Text(size=(23, 10)), sg.Button(u'历史最高', font=(u'宋体', 30), key='show_score'), sg.Text(size=(23, 10))], [ sg.Text(size=(70, 0)), sg.Image( filename=Game_Info.GAME_ICON_48, key='game_ico', enable_events=True ) ] ] def run(self): """启动游戏开始窗口""" self.window = sg.Window( title=self.title, icon=Game_Info.GAME_ICON, layout=self.layout ) self.__event_handler() def __event_handler(self): """窗口事件监听""" while True: event, value_dict = self.window.read(timeout=20) print(event, value_dict) # 静音控制 if self._voice_flag: self.window.find_element('voice_control').update(filename=Game_Info.VOICE_ICO) else: self.window.find_element('voice_control').update(filename=Game_Info.MUTE_ICO) if event in (sg.WIN_CLOSED, 'Quit'): break elif event in 'voice_control': self.voice_control() elif event in 'game_ico': self.author_win() elif event in 'start_game': print('开始游戏') self.window.Hide() TypingGame.game_over_flag = False TypingGame.game_quit_flag = False threading.Thread(target=self.start_game).start() # 利用线程开启游戏防止窗口卡死 elif event in 'game_set' or TypingGame.game_pause_flag: print('游戏设置') self.window.Disable() self.game_set() elif event in 'show_score': print('历史最高') self.window.Disable() self.show_score() elif TypingGame.game_quit_flag: self.window.UnHide() self.window.close() def voice_control(self): """游戏静音状态控制""" if self._voice_flag: GameStartWin._voice_flag = False self.window.find_element('voice_control').update(filename=Game_Info.MUTE_ICO) else: GameStartWin._voice_flag = True self.window.find_element('voice_control').update(filename=Game_Info.VOICE_ICO) def author_win(self): """游戏开发信息窗口""" self.window.Disable() game_conf = Game_Info.GameConfig() show_text = '游戏作者: \t' + game_conf.author + '\n\n'\ '游戏名称: \t' + game_conf.game_name + '\n\n'\ '游戏版本: \t' + game_conf.version + '\n\n'\ '作者邮箱: \t' + game_conf.e_mail + '\n' sg.Popup( show_text, title=u'关于作者', icon=Game_Info.GAME_ICON, font=(u'宋体', 18), custom_text=(u' ★ ', u' ❤ '), button_color=('red', '#063288'), line_width=50, ) self.window.Enable() def game_set(self): """游戏设置""" GameSetWin(u"游戏配置", self).run() def show_score(self): """查看历史最高分""" GameScoreWin(u'历史最高', self).run() @staticmethod def start_game(): """开始游戏""" TypingGame().start_game() @classmethod def voice_flag(cls): return cls._voice_flag class GameExecuteWin(object): """游戏运行窗口""" pass class GameEndWin(object): """游戏结束窗口""" def __init__(self): pass class GameSetWin(BaseWin): """游戏配置信息窗口""" # 游戏等级对照字典 game_level_dict = { 1: {"game_level_num": 5, "game_level_text": u"简单", "game_level_color": "green"}, 2: {"game_level_num": 15, "game_level_text": u"上手", "game_level_color": "blue"}, 3: {"game_level_num": 25, "game_level_text": u"中等", "game_level_color": "orange"}, 4: {"game_level_num": 35, "game_level_text": u"困难", "game_level_color": "red"}, 5: {"game_level_num": 50, "game_level_text": u"魔鬼", "game_level_color": "purple"} } def __init__(self, title, parent_win=None): """初始化游戏配置界面""" super().__init__(title) self.parent_win = parent_win self.word_normal_color = self.game_conf.word_normal_color self.spell_ok_color = self.game_conf.spell_ok_color self.__init_layout() def __init_layout(self): game_level_num = self.game_level_dict[int(self.game_conf.game_level)]["game_level_num"] game_level_text = self.game_level_dict[int(self.game_conf.game_level)]["game_level_text"] game_level_color = self.game_level_dict[int(self.game_conf.game_level)]["game_level_color"] self.layout = [ [ sg.Text(u'游戏难度等级:', text_color=self.text_color), sg.Slider( range=(1, 50), default_value=game_level_num, size=(26, 18), orientation='h', key="game_level", enable_events=True, disable_number_display=True, ), sg.Button( game_level_text, key='game_level_btn', button_color=(self.text_color, game_level_color), ), ], [ sg.Text(u'游戏字体大小:', text_color=self.text_color), sg.Slider( range=(15, 35), default_value=int(self.game_conf.word_size), size=(26, 18), enable_events=True, orientation='h', disable_number_display=True, key="word_size" ), sg.Text( str(self.game_conf.word_size), text_color=self.text_color, size=(3, 1), font=("宋体", int(self.game_conf.word_size)), key='word_size_num' ), ], [ sg.Text(u'游戏初始血条:', text_color=self.text_color), sg.Slider( range=(5, 30), default_value=int(self.game_conf.game_init_blood), size=(26, 18), orientation='h', enable_events=True, disable_number_display=True, key='init_blood' ), sg.Text( str(self.game_conf.game_init_blood), size=(3, 1), text_color=self.text_color, key='blood_num' ) ], [ sg.Text(u'游戏静音状态:', text_color=self.text_color), sg.Radio( ' ', default=GameStartWin.voice_flag(), key='voice_open', group_id=1, text_color=self.text_color, enable_events=True ), sg.Image(filename=Game_Info.VOICE_ICO), sg.Text(' ' * 5), sg.Radio( ' ', default=not GameStartWin.voice_flag(), key='mute', group_id=1, text_color=self.text_color, enable_events=True ), sg.Image(filename=Game_Info.MUTE_ICO) ], [ sg.Text(u'游戏字体颜色:', text_color=self.text_color), sg.Text( '', size=(17, 1), background_color=self.game_conf.word_normal_color, enable_events=True, key='word_normal_color' ), sg.Text( 'HUI', key='word_color_test', text_color=self.game_conf.word_normal_color, ), sg.Button(u'颜色选择', key='normal_ccb') ], [ sg.Text(u'单词拼写颜色:', text_color=self.text_color), sg.Text( '', size=(17, 1), background_color=self.game_conf.spell_ok_color, enable_events=True, key='spell_ok_color' ), sg.Text( 'HUI', key='spell_color_test', text_color=self.game_conf.spell_ok_color, ), sg.Button(u'颜色选择', key='spell_ccb') ], [ sg.Submit(u'暂时保存', key='temp_save', pad=((10, 350), (0, 0))), sg.Button(u'永久保存', key='permanent') ] ] def run(self): """开启游戏设置界面""" self.window = sg.Window( title=self.title, icon=Game_Info.GAME_ICON, layout=self.layout, font=("宋体", 18), element_padding=(10, 30), ) # 开启事件监听 self.__event_handler() @staticmethod def color_callback(color=None): """颜色按钮回调方法""" return colorchooser.askcolor(color) def __event_handler(self): while True: event, value_dict = self.window.read() # print(event, value_dict) if event in (None, 'Quit'): break elif event in ('voice_open', 'mute'): if value_dict['voice_open']: GameStartWin._voice_flag = True else: GameStartWin._voice_flag = False elif event in 'game_level': game_level = self.get_game_level(int(value_dict[event])) game_level_text = self.game_level_dict[game_level]['game_level_text'] game_level_color = self.game_level_dict[game_level]['game_level_color'] self.window.find_element('game_level_btn').update( game_level_text, button_color=(self.text_color, game_level_color) ) elif event in 'game_level_btn': # 点击按钮切换游戏等级 game_level = self.get_game_level(int(value_dict['game_level'])) if game_level == 5: game_level = 0 game_level_num = self.game_level_dict[game_level + 1]['game_level_num'] game_level_text = self.game_level_dict[game_level + 1]['game_level_text'] game_level_color = self.game_level_dict[game_level + 1]['game_level_color'] self.window.find_element('game_level').update(game_level_num) self.window.find_element('game_level_btn').update( game_level_text, button_color=(self.text_color, game_level_color) ) elif event in 'word_size': word_size_num = value_dict[event] self.window.find_element('word_size_num').update(int(word_size_num), font=(u'宋体', int(word_size_num))) elif event in 'init_blood': blood_num = int(value_dict[event]) self.window.find_element('blood_num').update(str(blood_num)) elif event in 'normal_ccb': # 游戏单词颜色选择 self.window.Disable() # 让游戏配置窗口不可用,不让用户乱点击,防止多开 choose_colors = self.color_callback(self.game_conf.word_normal_color) self.window.Enable() # 恢复游戏配置窗口 if None not in choose_colors: self.window.find_element('word_normal_color').update(background_color=choose_colors[1]) self.window.find_element('word_color_test').update(text_color=choose_colors[1]) self.word_normal_color = choose_colors[1] elif event in 'spell_ccb': # 单词拼写颜色选择 self.window.Disable() # 让游戏配置窗口不可用,不让用户乱点击,防止多开 choose_colors = self.color_callback(self.game_conf.spell_ok_color) self.window.Enable() # 恢复游戏配置窗口 if None not in choose_colors: self.window.find_element('spell_ok_color').update(background_color=choose_colors[1]) self.window.find_element('spell_color_test').update(text_color=choose_colors[1]) self.spell_ok_color = choose_colors[1] elif event in ('temp_save', 'permanent'): GameSetWin.SAVE_STATUS = True game_level = self.get_game_level(int(value_dict['game_level'])) value_dict['game_level'] = game_level value_dict['normal_ccb'] = self.word_normal_color value_dict['spell_ccb'] = self.spell_ok_color if event in 'temp_save': self.temp_save(value_dict) elif event in 'permanent': self.permanent(value_dict) break self.window.close() TypingGame.game_pause_flag = False # 恢复父窗口可用 if self.parent_win is not None: self.parent_win.window.Enable() def temp_save(self, game_dict): """临时保存游戏配置信息(临时有效,重开还原)""" """ { 'game_level': 2, 'word_size': 26.0, 'init_blood': 20.0, 'voice_open': True, 'mute': False, 'normal_ccb': '#00ffff', 'spell_ccb': '#ff0000' } """ self.game_conf.game_level = game_dict['game_level'] self.game_conf.word_size = game_dict['word_size'] self.game_conf.game_init_blood = game_dict['init_blood'] self.game_conf.word_normal_color = game_dict['normal_ccb'] self.game_conf.spell_ok_color = game_dict['spell_ccb'] def permanent(self, game_dict): """永久保存游戏配置信息(写入配置文件)""" # 修改配置文件 self.game_conf.set_game_level(game_dict['game_level']) self.game_conf.set_word_size(int(game_dict['word_size'])) self.game_conf.set_game_init_blood(int(game_dict['init_blood'])) self.game_conf.set_word_normal_color(game_dict['normal_ccb']) self.game_conf.set_spell_ok_color(game_dict['spell_ccb']) @staticmethod def get_game_level(data): game_level = 1 if data <= 10: game_level = 1 elif data <= 20: game_level = 2 elif data <= 30: game_level = 3 elif data <= 40: game_level = 4 elif data <= 50: game_level = 5 return game_level# class GameScoreWin(BaseWin): """游戏历史分数窗口""" heads = [ '{:4}'.format(u'游戏等级'), '{:4}'.format(u'最高分'), '{:6}'.format(u'耗 时'), '{:4}'.format(u'创建时间'), ] levels = ['level_1', 'level_2', 'level_3', 'level_4', 'level_5'] def __init__(self, title, parent_win=None): super().__init__(title) self.parent_win = parent_win self.__init_layout() def __init_layout(self): """初始化窗口布局""" score_dict = Game_Info.game_conf.history_score_dict # 游戏历史记录 level_0, level_1 = eval(score_dict[self.levels[0]]), eval(score_dict[self.levels[1]]) level_2, level_3 = eval(score_dict[self.levels[2]]), eval(score_dict[self.levels[3]]) level_4 = eval(score_dict[self.levels[4]]) header = [[sg.Text(h, pad=(31, 30)) for h in self.heads]] body = [ [ sg.Button(u'简单', button_color=('white', 'green')), sg.Text('{:4}'.format(str(level_0['score']))), sg.Text('{:6}'.format(str(level_0['use_time']))), sg.Text('{:4}'.format(str(level_0['create_time']))) ], [ sg.Button(u'上手', button_color=('white', 'blue')), sg.Text('{:4}'.format(str(level_1['score']))), sg.Text('{:6}'.format(str(level_1['use_time']))), sg.Text('{:4}'.format(str(level_1['create_time']))) ], [ sg.Button(u'中等', button_color=('white', 'orange')), sg.Text('{:4}'.format(str(level_2['score']))), sg.Text('{:6}'.format(str(level_2['use_time']))), sg.Text('{:4}'.format(str(level_2['create_time']))) ], [ sg.Button(u'困难', button_color=('white', 'red')), sg.Text('{:4}'.format(str(level_3['score']))), sg.Text('{:6}'.format(str(level_3['use_time']))), sg.Text('{:4}'.format(str(level_3['create_time']))) ], [ sg.Button(u'魔鬼', button_color=('white', 'purple')), sg.Text('{:4}'.format(str(level_4['score']))), sg.Text('{:6}'.format(str(level_4['use_time']))), sg.Text('{:4}'.format(str(level_4['create_time']))) ] ] self.layout = header + body def run(self): """启动游戏历史分数窗口""" self.window = sg.Window( title=self.title, icon=Game_Info.GAME_ICON, layout=self.layout, font=('宋体', 20), element_padding=(46, 30) ) self.__event_handler() def __event_handler(self): """窗口事件监听""" while True: event, value_dict = self.window.read() print(event, value_dict) if event in (sg.WIN_CLOSED, 'Quit'): self.parent_win.window.Enable() break self.window.close() def main(): GameStartWin(title="Word Sprite").run() if __name__ == '__main__': main() 4)PyGame游戏精灵模块 import pygame import random import Game_Info from Game_Info import GameConfig class BaseSprite(pygame.sprite.Sprite): """游戏精灵基类""" def __init__(self): super().__init__() self.image = None self.rect = None def set_pos(self, x, y): """设置精灵位置""" self.rect.x = x self.rect.y = y def hor_center(self, screen_rect): """ 水平居中显示 :param screen_rect: 游戏屏幕大小 :return: """ x = screen_rect.width / 2 - self.rect.width / 2 self.set_pos(x, self.rect.y) class ImageSprite(BaseSprite): """图片精灵基类""" def __init__(self, image): super().__init__() self.image = pygame.image.load(image) self.rect = self.image.get_rect() def transform_scale(self, image, size: tuple): """缩放图片大小""" self.image = pygame.transform.scale(image, size) self.rect = self.image.get_rect() class TextSprite(BaseSprite): """文字精灵基类""" def __init__(self, text, size=Game_Info.WORD_SIZE, color=Game_Info.WHITE): super().__init__() self.text = text self.size = size self.color = color # 创建字体 self.font = pygame.font.Font(Game_Info.GAME_FONT, self.size) # 根据字体创建显示对象(文字) render(self,text,antialias,color,background = None) self.image = self.font.render(text, True, self.color) self.rect = self.image.get_rect() def update(self, display_text): """更新显示的文字""" self.text = display_text rect_x = self.rect.x rect_y = self.rect.y self.image = self.font.render(self.text, True, self.color) self.rect = self.image.get_rect() self.rect.x = rect_x self.rect.y = rect_y class SpellSprite(TextSprite): """文字精灵基类""" def __init__(self, text, size=Game_Info.WORD_SIZE, color=Game_Info.WORD_SPELL_OK_COLOR): super().__init__(text, size, color) def update(self, display_text, color): """更新拼写的单词""" self.text = display_text self.color = color self.image = self.font.render(self.text, True, self.color) self.rect = self.image.get_rect() # 居中显示 self.hor_center(Game_Info.SCREEN_RECT) self.set_pos(self.rect.x, 40) class WordSprite(TextSprite): """单词精灵类""" game_conf = GameConfig() def __init__(self, text, cn_comment, speed: float, size=28, color=Game_Info.WORD_COLOR): super().__init__(text, size, color) self.speed = speed # 单词下落的速度 self.cn_comment = cn_comment # 英文单词的意思 self.y = float(self.rect.y) # 用小数存储单词降落的位置(方可设置成小数) def random_pos(self): """随机位置""" word_x = random.randint(0, Game_Info.SCREEN_RECT.width - self.rect.width) word_y = random.randint(-50, 10) self.rect.x = word_x self.rect.y = word_y self.y = float(self.rect.y) def update(self, game): """更新单词精灵""" # 判断游戏是否暂停 if game.game_pause_flag: self.speed = 0 else: self.y += self.speed self.rect.y = self.y # 超出游戏屏幕,删除精灵 if self.rect.y >= Game_Info.SCREEN_RECT.height: self.kill() # 根据不同游戏等级掉血 game.game_blood -= int(self.game_conf.game_level) * 3 # 游戏配置信息改变,更新单词 self.size = int(self.game_conf.word_size) self.font = pygame.font.Font(Game_Info.GAME_FONT, self.size) self.speed = game.game_level_dict[int(self.game_conf.game_level)]['word_fall_speed'] self.color = pygame.color.Color(self.game_conf.word_normal_color) # 游戏分数是10的倍数单词下落速度提升 if game.total_score > 0 and game.total_score % 100 == 0: self.speed += 0.5 # 游戏血条在[45 - 50]区间单词下落速度提升 if 45 * 10 <= game.game_blood <= 50 * 10: self.speed += 1 # 拼写的字母与单词匹配 if len(str(game.word_content)) >= 1 and \ str(game.word_content)[0].lower() in str(self.text)[0].lower() and \ str(game.word_content).lower() in str(self.text).lower(): self.color = pygame.color.Color(self.game_conf.spell_ok_color) # 更新单词颜色 self.image = self.font.render(self.text, True, self.color) class Animation(object): """动画特效类""" def __init__(self, screen): """初始化动画资源""" self.main_screen = screen # 加载动画资源 self.images = [pygame.image.load(img) for img in Game_Info.KILL_ANIMATION] # 设置当前动画播放索引 self.index = 0 # 动画播放间隔 self.interval = 2 self.interval_index = 0 # 动画位置 self.position = [0, 0] # 是否可见 self.visible = False # 设置动画播放的位置 def set_pos(self, x, y): self.position[0] = x self.position[1] = y # 动画播放 def action(self): # 如果爆炸对象状态不可见,则不计算坐标 if not self.visible: return # 控制每一帧图片的播放间隔 self.interval_index += 1 if self.interval_index < self.interval: return self.interval_index = 0 self.index = self.index + 1 if self.index >= len(self.images): self.index = 0 self.visible = False # 绘制动画 def draw(self): # 如果对象不可见,则不绘制 if not self.visible: return self.main_screen.screen.blit(self.images[self.index], (self.position[0], self.position[1])) def main(): pass if __name__ == '__main__': pass 五、效果展示 1)游戏界面

2)游戏设置

​3)随机截图

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

4)游戏结束

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

到此这篇关于基于Python实现英语单词小游戏的文章就介绍到这了,更多相关Python英语单词游戏内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



英语单词 小游戏 英语 单词 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号