彩色文字界面尼姆游戏(Python类 + mypycolor 工具协作打造)


相关笔记

  • 尼姆游戏(彩色文字界面版)(2022-08-26)
  • 尼姆游戏(优化版)(2021-12-08)
  • 尼姆游戏(首发)(2021-11-30)


  • 彩色文字界面

    尼 姆 游 戏

    (Python类 + mypycolor 工具协作打造)



    目 录


    1. “LJXFRUITMAN”给找到bug
    1. 引发我重写彩色界面版
    1. 函数式编程
    1. 机器聪明
    1. 游戏“困难模式”效果
    1. 游戏完整源码

  •   “LJXFRUITMAN”给我前面记的笔记《尼姆游戏(优化版)(2021-12-08)找到一个bug,困难模式下都是机器先手,“真人”没有赢的可能。

    笔记评论截屏图片


    回页首


    激发我重写彩色文字界面版

      在修复bug的时候,感觉到尼姆游戏(优化版)“代码还有很大优化空间,逻辑也有些许混乱”,这是由于当时“基础还不太熟”。看着“灰白”的文字界面,又想起前不久完成优化的色彩控制工具mypycolor,就想要用渐渐熟悉起来的class + mypyolor协同打造彩色文字界面版“尼姆游戏”。文字界面也用最近沉淀的“技巧”,打造一个固定不变的界面header。经过一番努力尝试,header还嵌入“尼姆游戏”的规则。

    header效果截屏图片

    header代码

    
    
    def clear(): clear = system('clear') # Linux清屏。
    
    
    class Nimb:
    
        readme = f"\n{'':>13}{localtime_show()}\n{color('(Author: Dream elf cq)'.center(50), 30, 100, 7)}{color('~'*50, 30, 100, 7)}\n{color('尼 姆 游 戏'.center(46), 92)}\n{color('(Nimb game)'.center(50), 34, 2)}\n\n{'':>4}尼姆游戏,是一个著名的游戏,有很多变种玩法。\n{'':>4}两个玩家轮流从一堆物品中拿走一部分。在每一步中,玩家可以自由选择拿走多少物品,但是必须至少拿走一个并且最多只能拿走一半物品,然后轮到对手。拿走最后一个物品的玩家输掉游戏。\n{'':>4}谁先手,我用{color(' Python ', 32)}内建随机函数{color(' random.choice (“机器”,  “玩家”) ', 32)}随机方法选择。\n{color('~'*50, 30, 100, 7)}"
    
        def head(self): # 打印游戏规则及说明。
            clear()
            print(self.readme)
    
    

    回页首


    函数式编程

      我决定用“函数式编程”来结构我的Nimb game,我用 class Nimb: 组织代码,每个方法完成一个“小功能”,最后直接“组装”。

    help(Nimb)得到的 class Nimb: 方法清单

    游戏主模块play代码

        def play(self, rank=(0,)): # 游戏取物主模块,默认“幼稚”级别。
            computer_name = self.name_computer()
            player = choice(('您', computer_name))
            rank = list(rank)
    
            while True:
                self.clear()
                if player == computer_name:
                    shuffle(rank) # 打乱待选机率列表。
                    way = choice(rank)
                    if way == 0:
                        take = self.random_take()
                    elif way == 1:
                        take = self.clever_take()
                    input(f"{'':>14}机器取物:{color(take, 92)}")
                    self.num = self.num - take
                    player = '您' # 当前玩家切换。
                else:
                    take = self.person_take()
                    self.num = self.num - take
                    player = computer_name # 当前玩家切换。
                if not self.num:
                    break
    
            self.iswin(player)
    

    游戏“真人取物”模块person_take代码

        def person_take(self): # 真人玩家取物。
            self.clear()
            
            while True:
                try:
                    take = int(input(f"{'':>14}{color('您取物: ', 92, 3)}"))
                    if take > self.num or take < 1 or self.num > 1 and take > int(self.num/2):
                        error_show('取物')
                        self.clear()
                        continue 
                except Exception as error:
                    print(f"ErrorType: {color(error, 31)}")
                    error_show('输入')
                    self.clear()
                    continue 
                break
    
            return take
    

    回页首


    机器聪明取物

    机器聪明取物代码

    
        def clever_take(self): # 机器聪明取物。
            self.clear()
            num = self.num
    
            for i in  range(num): # 注意:三个 if 顺序不可以变动!首先检查物品现存数为1~3或者2的幂次方少1的情况。1~3,只能取1,后者取1,才是必胜局。再检查必输局的情况。现存物品数为2的幂次方少1,随机取物,期待对手疏漏。最后是“聪明”正常取物,取物后让现存物品数为2的幂次方少1,造就必胜局。
                if 2**i == num or num < 4:
                    return 1 # 当物品现存数为2的幂次方或者小于4时,只取1。
                elif 2**i - 1 == num:
                    return choice(range(1, int(num/2))) # 当物品现存数为2的幂次方少1时,是必输局,随机取物。
                elif 2**i > num:
                    return num - (2**(i-1)-1) # 让取物后现存物品数为2的幂次方少1,呈必胜局。
    
    

    注意:

    三个 if 顺序不可以变动!

  • 1、首先检查物品现存数为1~3或者2的幂次方少1的情况。1~3,只能取1,后者取1,才是必胜局。
  • 2、再检查必输局的情况。现存物品数为2的幂次方少1,随机取物,期待对手疏漏,截取翻身机会。
  • 3、最后是“聪明”正常取物,取物后让现存物品数为2的幂次方少1,造就必胜局。

  • 回页首


    游戏“困难模式”效果

    游戏部分效果截屏图片




    回页首


    游戏完整源码跳过源码

    #/sur/bin/nve python
    # coding: utf-8
    
    
    '''
    filename = 'nimb_game.py'
    author = 'dream elf cq'
    time = '2002-08-24'
    '''
    
    
    from os import system # 加载python命令运行“容器”os.system方法。
    from random import choice # 加载random模块choice随机选择方法。
    from random import shuffle # 加载random模块shuffle洗牌方法。
    from time import localtime # 加载当前时间数组获取方法。
    
    
    from lib.mypycolor import Color # 加载自制色彩控制打印工具。
    color = Color().set_color # 方法别名,方便调用。
    
    
    def clear(): clear = system('clear') # Linux清屏。
    
    
    def localtime_show(): # 获取当前时间格式化字符串。
        t = localtime()
        time = ':'.join(map(lambda x: f"{x:0>2}", t[3:6]))
        year, month, day = t[:3]
        date = f"{year}年{month:0>2}月{day:0>2}日"
        return f"{color(time, 34)}  {color(date, 34, 2)}"
    
    
    def error_show(string): # 错误提示。
        tip = f" {string}错误!".center(45, '~')
        input(f"{color(tip, 91, 43)}\n")
    
    
    class Nimb:
        '''
    
                       尼 姆 游 戏                                       (Nimb game)                                                                          尼姆游戏,这是一个著名的游戏,有很多变种玩法。
        两个玩家轮流从一堆物品中拿走一部分。在每一步中,玩家可以自由选择拿走多少物品,但是必须至少拿走一个并且最多只能拿走一半物品,然后轮到对手。拿走最后一个物品的玩家输掉游戏。
        谁先手,我用 Python 内建随机函数 random.choice (“机器”,  “玩家”) 随机方法选择。
    
                  (Author: Dream elf cq)
    
    '''
        readme = f"\n{'':>13}{localtime_show()}\n{color('(Author: Dream elf cq)'.center(50), 30, 100, 7)}{color('~'*50, 30, 100, 7)}\n{color('尼 姆 游 戏'.center(46), 92)}\n{color('(Nimb game)'.center(50), 34, 2)}\n\n{'':>4}尼姆游戏,这是一个著名的游戏,有很多变种玩法。\n{'':>4}两个玩家轮流从一堆物品中拿走一部分。在每一步中,玩家可以自由选择拿走多少物品,但是必须至少拿走一个并且最多只能拿走一半物品,然后轮到对手。拿走最后一个物品的玩家输掉游戏。\n{'':>4}谁先手,我用{color(' Python ', 32)}内建随机函数{color(' random.choice (“机器”,  “玩家”) ', 32)}随机方法选择。\n{color('~'*50, 30, 100, 7)}"
        computer_names = ('小精灵', '小阔爱', '小乖乖', '小王子', '小仙女', '观音大士', '女神🤩', '重庆崽儿', '梦幻精灵cq', '八爪章鱼', '齐天大圣', '皇阿玛', '小燕子', '小傻瓜', '红苕花', '白马王子')
        model = ''
        num = ''
    
        def head(self): # 打印游戏规则及说明。
            clear()
            print(self.readme)
    
        def num_show(self): # 打印游戏模式及现在物品数量。
            model = f"【{self.model}模式】".center(44, '-')
            print(f"\n{color(model, 92)}\n\n{'':>14}现存物品数:{color(self.num, 92)}\n{color('-'*50, 30, 100, 7)}")
    
        def clear(self): # 打印游戏界石头部信息及现存物品数量。
            self.head()
            self.num_show()
    
        def person_take(self): # 真人玩家取物。
            self.clear()
            
            while True:
                try:
                    take = int(input(f"{'':>14}{color('您取物: ', 92, 3)}"))
                    if take > self.num or take < 1 or self.num > 1 and take > int(self.num/2):
                        error_show('取物')
                        self.clear()
                        continue 
                except Exception as error:
                    print(f"ErrorType: {color(error, 31)}")
                    error_show('输入')
                    self.clear()
                    continue 
                break
    
            return take
    
        def random_take(self): # 机器随机取物。
    
            if self.num < 4: take = 1
            else:
                take = choice(range(1, int(self.num/2)+1))
    
            return take
    
        def clever_take(self): # 机器聪明取物。
            self.clear()
            num = self.num
    
            for i in  range(num): # 注意:三个if顺序不可以变动!首先检查物品现存数为1~3或者2的幂次方少1的情况。1~3,只能取1,后者取1,才是必胜局。再检查必输局的情况。现存物品数为2的幂次方少1,随机取物,期待对手疏漏。最后是“聪明”正常取物,取物后让现存物品数为2的幂次方少1,造就必胜局。
                if 2**i == num or num < 4:
                    return 1 # 当物品现存数为2的幂次方或者小于4时,只取1。
                elif 2**i - 1 == num:
                    return choice(range(1, int(num/2))) # 当物品现存数为2的幂次方少1时,是必输局,随机取物。
                elif 2**i > num:
                    return num - (2**(i-1)-1) # 让取物后现存物品数为2的幂次方少1,呈必胜局。
    
        def menu_show(self): # 游戏菜单展示。
            self.head()
            print(' '*8, end='')
            print('  '.join(map(lambda x,y: f"{x}. {color(y, 92)}", list('1230'), ('幼稚', '简单', '困难', '退出'))))
            print(color('-'*50, 30, 100, 7))
    
        def name_computer(self): # 机器对手名字设定。
            computer_name = input(f"\n{color(' 使用内置名字直接确认 '.center(40, '-'), 30, 100, 7)}\n{'':>14}{color('给机器对手命名:', 92, 3)}").strip()
            if not computer_name:
                computer_name = choice(self.computer_names)
            input(f"\n{color('-'*50, 32, 2)}\n{'':>16}您将与{color(computer_name, 92)}对局。\n{color('-'*50, 32, 2)}")
            return computer_name
    
        def iswin(self, winer): input(f"\n{color('-'*50, 33, 2)}\n{'':>20}{color(winer + ' ', 92, 3)}{color('赢了!', 91, 43, 5)}\n{color('-'*50, 2, 33)}\n") # 打印赢家。
    
        def play(self, rank=(0,)): # 游戏取物主模块,默认“幼稚”级别。
            computer_name = self.name_computer()
            player = choice(('您', computer_name))
            rank = list(rank)
    
            while True:
                self.clear()
                if player == computer_name:
                    shuffle(rank) # 打乱待选机率列表。
                    way = choice(rank)
                    if way == 0:
                        take = self.random_take()
                    elif way == 1:
                        take = self.clever_take()
                    input(f"{'':>14}机器取物:{color(take, 92)}")
                    self.num = self.num - take
                    player = '您' # 当前玩家切换。
                else:
                    take = self.person_take()
                    self.num = self.num - take
                    player = computer_name # 当前玩家切换。
                if not self.num:
                    break
    
            self.iswin(player)
    
        def naive(self): # 幼稚级别游戏模块。
            self.model = '幼稚'
            self.num = choice(range(1, 201))
            self.play()
    
        def easy(self): # 简单级别游戏模块,36%机率机器“聪明”取物。
            self.model = '简单'
            self.num = choice(range(201, 501))
            self.play(([1]*36 + [0]*64))
    
        def hard(self): # 困难级别游戏模块,92%机率机器“聪明”取物。
            self.model = '困难'
            self.num = choice(range(501, 1501))
            self.play([0]*8 + [1]*92)
    
        def ismenu(self): # 菜单确认,据菜单选择,执行相应游戏模块。
            while True:
                self.menu_show()
                try:
                    menu_choice = int(input(f"{'':>14}{color('菜单选择: ', 92, 3)}"))
                    if menu_choice not in range(4):
                        error_show('选取')
                        self.clear()
                        continue 
                except Exception as error:
                    print(f"ErrorType: {color(error, 31)}")
                    error_show('输入')
                    self.clear()
                    continue 
                break
            if menu_choice == 0:
                self.head()
                print(f"\n{'':>14}{color('谢谢您体验“尼姆游戏”!', 95, 3)}\n{color('~'*50, 30, 100, 7)}\n{color('Author: Dream Elf cq, Tester: Liuyi'.center(50), 34, 2)}\n{color('-'*50, 30, 100, 7)}\n")
                exit()
            elif menu_choice == 1:
                self.naive()
            elif menu_choice == 2:
                self.easy()
            elif menu_choice == 3:
                self.hard()
    
        def start(self): # 游戏主循环模块。
            while True:
                self.ismenu()
    
    
    if __name__ == '__main__': # 直接运行本*.py文件,则启动游戏。
        Nimb().start()
    
    
    物联沃分享整理
    物联沃-IOTWORD物联网 » 彩色文字界面尼姆游戏(Python类 + mypycolor 工具协作打造)

    发表回复