1-Python - 猜灯谜

依赖

pip install pygame

还需要本地同级目录有个simfang.ttf文件搭配,也可以有个MP3音乐文件搭配。
百度云链接: 提取码: ptzk

代码示例


import os
import sys
import pygame
import random

data = [
    {
        'quesion': '黑嘴雀,落田渦,食水少,講話多(打一文具)',
        'options': ['鋼筆', '毛筆', '鉛筆', '墨水'],
        'answer': 1
    },
    {
        'quesion': '發言音太輕,聽眾有意見(打一成語)',
        'options': ['人微言輕', '眾口難調', '不盡人意', '低聲下氣'],
        'answer': 3
    },
    {
        'quesion': '閉口不言只管笑(打一字)',
        'options': ['答', '合', '哈', '吞'],
        'answer': 2
    },
    {
        'quesion': '張清在前,秦明斷後(打二字中國城市)',
        'options': ['洛陽', '青島', '長春', '南京'],
        'answer': 2
    },
    {
        'quesion': '冤情由來(打二字古代人名)',
        'options': ['竇娥', '魏延', '岳飛', '屈原'],
        'answer': 3
    },
    {
        'quesion': '外青內白胖娃娃,酒席上面愛雕花(打一蔬菜)',
        'options': ['蘿蔔', '冬瓜', '黃瓜', '苦瓜'],
        'answer': 1
    },
    {
        'quesion': '十字對十字,太陽對月亮(猜一個字)',
        'options': ['明', '早', '朝', '脾'],
        'answer': 2
    },
    {
        'quesion': '中心要點 (打一字)',
        'options': ['忠', '小', '卜', '重'],
        'answer': 2
    },
    {
        'quesion': '日落香殘,洗卻凡心一點(猜一字)',
        'options': ['禿', '旻', '頹', '嘰'],
        'answer': 0
    },
    {
        'quesion': '既有頭,又有尾,中間生四張嘴(猜一字)',
        'options': ['田', '申', '由', '晶'],
        'answer': 1
    },
    {
        'quesion': '二間屋仔窄一窄,裡面住著十個人客(打一生活物冠量)',
        'options': ['手套', '文具盒', '一對鞋', '化妝包'],
        'answer': 2
    },
    {
        'quesion': '一點一畫長,二畫口四方,五月荔枝熟,媽(張)開口來裝(打一字)',
        'options': ['唔', '吾', '語', '焐'],
        'answer': 2
    },
    {
        'quesion': '麥兜自己沖涼(打一作家)',
        'options': ['麥佳碧', '朱熹', '李清照', '朱自清'],
        'answer': 3
    },
    {
        'quesion': '一個「不」出頭,二個「不」出頭,三個「不」出頭,唔系唔出頭,實系「不」出頭(打一字)',
        'options': ['森', '丕', '林', '歪'],
        'answer': 0
    },
    {
        'quesion': '濕濕瀝瀝,連毛塞入;唔怕腰骨痛,只要子孫密(猜一勞作行為)',
        'options': ['鑿井', '耕田', '插秧', '撈魚'],
        'answer': 2
    },
    {
        'quesion': '闔盅合(蓋)闔盅,裡而有個豆皮翁。(打一植物果實)',
        'options': ['核桃', '花生', '荷蘭豆', '榴蓮'],
        'answer': 0
    },
    {
        'quesion': '艇仔合(蓋)艇仔,裡面有兩個孖仔。(打一農作物)',
        'options': ['荷蘭豆', '黃豆', '花生', '菱角'],
        'answer': 2
    },
    {
        'quesion': '主人微笑(打一地名)',
        'options': ['嘉興', '安徽', '東京', '東莞'],
        'answer': 3
    },
    {
        'quesion': '鍵盤入面邊個掣最靚仔?',
        'options': ['8', 'F8', 'F12', 'F4'],
        'answer': 3
    },
    {
        'quesion': '咩豬系冇腳?',
        'options': ['蜘蛛', '存錢豬', '珍珠', '羅志祥'],
        'answer': 2
    },
    {
        'quesion': '爺爺的兒子(打一種食物)',
        'options': ['包子', '椰子', '車仔面', '芭樂'],
        'answer': 1
    },
    {
        'quesion': '一間屋,三個門,裡面只住半個人。(猜一用品)',
        'options': ['T-恤', '手套', '褲子', '襪子'],
        'answer': 2
    },
    {
        'quesion': '拱豬入門(打一字)',
        'options': ['間', '閡', '闔', '閉'],
        'answer': 1
    },
    {
        'quesion': '皇帝新衣。(打一字)',
        'options': ['無', '假', '襲', '謊'],
        'answer': 2
    },
    {
        'quesion': '香港的肥仔多數姓什乜?',
        'options': ['肥', '胖', '大', '死'],
        'answer': 3
    }
]

'''按钮类'''


class Button(pygame.sprite.Sprite):
    def __init__(self, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        if kwargs.get('font') is None:
            self.font = pygame.font.Font(kwargs.get('font_path'), kwargs.get('font_size'))
        else:
            self.font = kwargs.get('font')
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.red = (255, 0, 0)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 255)
        self.cyan = (0, 255, 255)
        self.text = kwargs.get('text')
        self.image = self.font.render(self.text, True, self.white)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = kwargs.get('position')

    '''画到屏幕上'''

    def draw(self, screen):
        screen.blit(self.image, self.rect)

    '''更新'''

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.image = self.font.render(self.text, True, self.cyan)
        else:
            self.image = self.font.render(self.text, True, self.white)


'''定义一些常量'''
DeepSkyBlue = (0, 191, 255)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
MediumOrchid = (186, 85, 211)
riddles_list = data
random.shuffle(riddles_list)
font_path = os.path.join(os.getcwd(), 'simfang.ttf')

'''开始界面'''


class startInterface():
    def __init__(self, screen, **kwargs):
        self.text1 = '猜 灯 谜'
        self.text2 = '开始游戏'
        self.text3 = '退出游戏'
        self.screen = screen

    def start(self):
        button_groups = pygame.sprite.Group()
        button_start = Button(font_path=font_path, font_size=24, text=self.text2, position=(236, 300))
        button_quit = Button(font_path=font_path, font_size=24, text=self.text3, position=(464, 300))
        button_groups.add(button_start)
        button_groups.add(button_quit)
        font = pygame.font.Font(font_path, 48)
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        mouse_pos = pygame.mouse.get_pos()
                        if button_start.rect.collidepoint(mouse_pos):
                            return
                        elif button_quit.rect.collidepoint(mouse_pos):
                            pygame.quit()
                            sys.exit()
            self.screen.fill((0, 0, 0))
            title = font.render(self.text1, True, DeepSkyBlue)
            self.screen.blit(title, (302, 150))
            button_groups.update()
            button_groups.draw(self.screen)
            pygame.display.update()
            clock.tick(60)


'''结束界面'''


class endInterface():
    def __init__(self, screen, num_correct, num_total, **kwargs):
        self.text1 = '恭喜你猜完了所有灯谜'
        self.text2 = '答对的灯谜数量: %s' % num_correct
        self.text3 = '灯谜总数量: %s' % num_total
        self.text4 = '正确率: %.2f%%' % (num_correct * 100 / num_total)
        self.screen = screen

    def start(self):
        button_groups = pygame.sprite.Group()
        button_restart = Button(font_path=font_path, font_size=24, text='重新开始', position=(236, 400))
        button_quit = Button(font_path=font_path, font_size=24, text='退出游戏', position=(464, 400))
        button_groups.add(button_restart)
        button_groups.add(button_quit)
        font_big = pygame.font.Font(font_path, 32)
        font = pygame.font.Font(font_path, 24)
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        mouse_pos = pygame.mouse.get_pos()
                        if button_restart.rect.collidepoint(mouse_pos):
                            startGuess()
                        elif button_quit.rect.collidepoint(mouse_pos):
                            pygame.quit()
                            sys.exit()
            self.screen.fill((0, 0, 0))
            text1_render = font_big.render(self.text1, True, DeepSkyBlue)
            text2_render = font.render(self.text2, True, DeepSkyBlue)
            text3_render = font.render(self.text3, True, DeepSkyBlue)
            text4_render = font.render(self.text4, True, DeepSkyBlue)
            self.screen.blit(text1_render, (250, 100))
            self.screen.blit(text2_render, (250, 200))
            self.screen.blit(text3_render, (250, 240))
            self.screen.blit(text4_render, (250, 280))
            button_groups.update()
            button_groups.draw(self.screen)
            pygame.display.update()
            clock.tick(60)


'''获得一个灯谜'''


def getRiddle(riddle_idx):
    if riddle_idx == len(riddles_list):
        return None
    return riddles_list[riddle_idx]


'''开始猜灯谜'''


def startGuess():
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('猜灯谜-微信公众号: Charles的皮卡丘')
    # pygame.mixer.music.load((os.path.join(os.getcwd(), 'bg.mp3')))
    # pygame.mixer.music.set_volume(0.4)
    # pygame.mixer.music.play(-1)
    clock = pygame.time.Clock()
    startInterface(screen).start()
    riddle_idx = 0
    one_riddle = getRiddle(riddle_idx)
    num_correct = 0
    font = pygame.font.Font(font_path, 24)
    font_big = pygame.font.Font(font_path, 32)
    flag = False
    time_count = 0
    while True:
        button_choice1 = Button(font=font, text='A. ' + one_riddle.get('options')[0], position=(100, 250))
        button_choice2 = Button(font=font, text='B. ' + one_riddle.get('options')[1], position=(100, 290))
        button_choice3 = Button(font=font, text='C. ' + one_riddle.get('options')[2], position=(100, 330))
        button_choice4 = Button(font=font, text='D. ' + one_riddle.get('options')[3], position=(100, 370))
        button_groups = pygame.sprite.Group()
        button_groups.add(button_choice1, button_choice2, button_choice3, button_choice4)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if not flag:
                        mouse_pos = pygame.mouse.get_pos()
                        answer = one_riddle.get('answer')
                        if button_choice1.rect.collidepoint(mouse_pos):
                            flag = True
                            if answer == 0:
                                text = '恭喜你, 答对了本题'
                                num_correct += 1
                            else:
                                text = '很遗憾, 答错了本题'
                        elif button_choice2.rect.collidepoint(mouse_pos):
                            flag = True
                            if answer == 1:
                                text = '恭喜你, 答对了本题'
                                num_correct += 1
                            else:
                                text = '很遗憾, 答错了本题'
                        elif button_choice3.rect.collidepoint(mouse_pos):
                            flag = True
                            if answer == 2:
                                text = '恭喜你, 答对了本题'
                                num_correct += 1
                            else:
                                text = '很遗憾, 答错了本题'
                        elif button_choice4.rect.collidepoint(mouse_pos):
                            flag = True
                            if answer == 3:
                                text = '恭喜你, 答对了本题'
                                num_correct += 1
                            else:
                                text = '很遗憾, 答错了本题'
        screen.fill((0, 0, 0))
        if not flag:
            riddle_content1 = '灯谜: '
            riddle_content2_1 = one_riddle.get('quesion')[:len(one_riddle.get('quesion')) // 2]
            riddle_content2_2 = one_riddle.get('quesion')[len(one_riddle.get('quesion')) // 2:]
            riddle_content3 = '选项: '
            riddle_content1_render = font.render(riddle_content1, True, MediumOrchid)
            riddle_content2_1_render = font.render(riddle_content2_1, True, MediumOrchid)
            riddle_content2_2_render = font.render(riddle_content2_2, True, MediumOrchid)
            riddle_content3_render = font.render(riddle_content3, True, MediumOrchid)
            screen.blit(riddle_content1_render, (60, 80))
            screen.blit(riddle_content2_1_render, (60, 120))
            screen.blit(riddle_content2_2_render, (60, 150))
            screen.blit(riddle_content3_render, (60, 210))
            button_groups.update()
            button_groups.draw(screen)
        else:
            time_count += 1
            if time_count > 60:
                flag = False
                time_count = 0
                riddle_idx += 1
                one_riddle = getRiddle(riddle_idx)
                if one_riddle is None:
                    endInterface(screen, num_correct, len(riddles_list)).start()
            else:
                text_render = font_big.render(text, True, RED)
                screen.blit(text_render, (160, 250))
        pygame.draw.line(screen, WHITE, (600, 0), (600, 600), 5)
        score_text = '答对灯谜数: %s' % num_correct
        score_text_render = font.render(score_text, True, WHITE)
        screen.blit(score_text_render, (620, 100))
        pygame.display.update()
        clock.tick(60)


if __name__ == '__main__':
    startGuess()


参考:Charles的皮卡丘
posted @ 2019-03-06 23:54  听雨危楼  阅读(436)  评论(0编辑  收藏  举报