PHP前端开发

如何用Python和Pygame来创建一个简单的单词游戏

百变鹏仔 1个月前 (01-21) #Python
文章标签 创建一个

一、环境准备

1)运行环境 

环境安装:python 3.8: 解释器、pycharm: 代码编辑器、pygame、numpy、部分自带的模块直接安装Python就可以使用了。

 2)模块安装

 第三方库的安装方式如下:

 一般安装:pip install +模块名 镜像源安装:pip install -i 

立即学习“Python免费学习笔记(深入)”;

pypi.douban.com/simple/+模块名 (还有很多国内镜像源,这里是豆瓣的用习惯了) 

3)图片文字素材等

二、代码展示

主程序——

import pygameimport sysimport tracebackimport osfrom pygame.locals import *from random import *import numpy as npimport linecachepygame.init()  # 游戏初始化pygame.mixer.init()  # 音效初始化bg_size = width, height = 480, 700  # 屏幕大小screen = pygame.display.set_mode(bg_size)pygame.display.set_caption("英语单词挑战")  # 标题# 背景图片background = pygame.image.load("source/背景.png")  # .convert()BLACK = (0, 0, 0)WHITE = (255, 255, 255)GREEN = (0, 255, 0)RED = (255, 0, 0)# 游戏音乐pygame.mixer.music.load("source/背景音乐.mp3")pygame.mixer.music.set_volume(0.2)success_sound = pygame.mixer.Sound("source/正确.wav")success_sound.set_volume(0.2)lost_sound = pygame.mixer.Sound("source/失败.wav")lost_sound.set_volume(0.2)win_sound = pygame.mixer.Sound("source/胜利.wav")win_sound.set_volume(0.2)class Word(pygame.sprite.Sprite):    def __init__(self, bg_size, showword):        pygame.sprite.Sprite.__init__(self)        self.word = showword  # 获取单词        self.length = len(self.word)  # 单词长度        self.wordfont = pygame.font.SysFont("arial", 36)  # 使用系统字体        self.wordtext = self.wordfont.render(self.word, True, WHITE, BLACK)  # 单词        self.promptword = "*"*self.length        self.showtext = self.wordfont.render(self.promptword, True, WHITE, BLACK)  # 隐藏单词        self.succtext = self.wordfont.render("", True, WHITE)        self.rect = self.wordtext.get_rect()  # 单词坐标        self.width, self.height = bg_size[0], bg_size[1]        self.rect.left, self.rect.top = (self.width - self.rect.width) // 2, 20  # 定义坐标        self.speed = 1  # 下移速度        # self.destroy_images = []        # self.destroy_images.extend([pygame.image.load("爆炸小.png").convert_alpha()])        self.active = True  # 活动标志        self.success = False  # 正确标志    # 判断输入字母是否正确,并显示    def show(self, a):        for i in range(self.length):            if self.promptword[i] == "*":                if self.word[i] == a:                    self.promptword =self.promptword[:i] + a + self.promptword[i+1:]                    self.showtext = self.wordfont.render(self.promptword, True, WHITE, BLACK)  # 隐藏单词                if self.promptword == self.word:                    self.success = True                break            else:                continue    # 单词移动    def move(self):        if self.rect.top  0.8:            rate_color = GREEN        else:            rate_color = RED        pygame.draw.rect(screen, rate_color, ((10, 60), (200 * rate, 20)), 0)  # 填充        remaintext = myfont_small.render(f"{rate*100:.2f}%", True, WHITE)        screen.blit(remaintext, (220, 55))        if not paused and not mained:            if not flag:                # 生成单词                showword = np.random.choice(list(mydict.keys()))  # 随机选择单词                showprompt = mydict[showword]  # 单词中文提示                # print(showword, showprompt)                myword = Word(bg_size, showword)  # 生成单词                flag = True  # 新单词            else:                myword.move()  # 单词向下移动                myword.describe(showprompt)                myword.show(keyvalue)  # 获取键盘按键                if promptflag:                    screen.blit(myword.wordtext, myword.rect)                else:                    screen.blit(myword.showtext, myword.rect)                    # 成功                    if myword.success:                        screen.blit(myword.succtext, myword.rect)  # 清空                        screen.blit(success_image, myword.rect)  # 成功图片                        success_sound.play()                        if not (delay % 10):  # 延时                            myword.reset()                            flag = False                            score += 5                            getnum += 1                            del mydict[showword]                            if getnum == num:                                winflag = True                                mained = True                if nextflag:                    myword.reset()                    flag = False                    nextflag = False                if myword.rect.top > height - 118:                    lost_sound.play()                    flag = False                    score -= 2        # 暂停时        elif paused and not mained:            myword.active = False            screen.blit(myword.showtext, myword.rect)            myword.describe(showprompt)        # 显示主页        elif mained and not winflag:            # myword.active = False            screen.blit(background, (0, 0))  # 载入背景图片            # 绘制结束界面            # 更新最高分            if score > record_score:                record_score = score            # 更新进度            if rate > record_rate:                record_rate = rate            # 最高分            record_score_text = myfont_big.render(f"Highest Score:{record_score}", True, WHITE)            screen.blit(record_score_text, (50, 50))            # 最高进度            record_rate_text = myfont_big.render(f"Highest Rate:{record_rate*100:.2f}%", True, WHITE)            screen.blit(record_rate_text, (50, 100))            # 当前得分            nowscore_text1 = myfont_big.render("Your Score:", True, WHITE)            nowscore_text1_rect = nowscore_text1.get_rect()            nowscore_text1_rect.left, nowscore_text1_rect.top = 50, 150            screen.blit(nowscore_text1, nowscore_text1_rect)            nowscore_text2 = myfont_big.render(str(score), True, RED)            nowscore_text2_rect = nowscore_text2.get_rect()            nowscore_text2_rect.left, nowscore_text2_rect.top = 50 + nowscore_text1_rect.width, nowscore_text1_rect.top            screen.blit(nowscore_text2, nowscore_text2_rect)            # 当前进度            nowrate_text1 = myfont_big.render("Your Rate:", True, WHITE)            nowrate_text1_rect = nowrate_text1.get_rect()            nowrate_text1_rect.left, nowrate_text1_rect.top = 50, 200            screen.blit(nowrate_text1, nowrate_text1_rect)            nowrate_text2 = myfont_big.render(f"{rate*100:.2f}%", True, RED)            nowrate_text2_rect = nowrate_text2.get_rect()            nowrate_text2_rect.left, nowrate_text2_rect.top = 50 + nowrate_text1_rect.width, nowrate_text1_rect.top            screen.blit(nowrate_text2, nowrate_text2_rect)            # 继续游戏            goon_rect.left, goon_rect.top = (width - goon_rect.width) // 2, 300            screen.blit(goon_image, goon_rect)            # 重新开始            restart_rect.left, restart_rect.top = (width - restart_rect.width) // 2, goon_rect.bottom + 20            screen.blit(restart_image, restart_rect)            # 结束游戏            gameover_rect.left, gameover_rect.top = (width - gameover_rect.width) // 2, restart_rect.bottom + 20            screen.blit(gameover_image, gameover_rect)            # 检测用户鼠标操作            # 如果用户按下鼠标左键            if pygame.mouse.get_pressed()[0]:                # 获取鼠标位置                pos = pygame.mouse.get_pos()                # 如果用户点击继续游戏                if goon_rect.left  record_score:                        record_score = score                    # 写入记录文件                    with open(historyfile, mode='w', encoding='utf-8') as f:                        f.write(str(record_score))                        f.write("")                        f.write(str(record_rate))                        f.close()                    # 保存剩余单词                    SaveDict(mydict, myfile)                    # 退出主页                    mained = False                    score = 0                    mydict = Getletters(olingefile)  # 获取原始单词                    getnum = 0                # 如果用户点击结束游戏                elif gameover_rect.left