首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >RockPaperScissorsV2后续进阶

RockPaperScissorsV2后续进阶
EN

Code Review用户
提问于 2015-11-12 17:18:27
回答 1查看 264关注 0票数 1

我已经发布了我的第一个版本 of RockPaperScissors一段时间前。它是在一个旧版本的python上,不正确地使用了一些功能。该版本被更新为最新版本的python,并为在终端上运行的用户提供了一些额外的服务。有什么需要添加或修改的吗?我的课用得对吗?有虫子吗?总体上有什么改进吗?

代码语言:javascript
运行
复制
# Programmer: DeliriousSyntax
# Date: October 30, 2015
# File: RockPaperScissorsV2-py3.py

# This is a classic game of rock paper scissors.

import random
import shelve
import time
import colorama
import sys




class Scorecard(dict):
    """Stores all items related to "Score\""""

    def __init__(self, **kwargs):
        """Makes all values set to 0"""
        super().__init__(**kwargs)
        for key in ('rounds', 'losses', 'wins', 'draws', 'games_won',
                    'games_lost', 'games_played', "total_rounds",
                    'rounds_won', 'rounds_lost', 'rounds_tied', 'game_draws'):
            self[key] = 0

    def reset(self):
        """Resets the scores for next game"""
        for key in ('rounds', 'losses', 'wins', 'draws'):
            self[key] = 0

    def round_update(self, result):
        """Updates the info for each round
        :param result:
        """
        self['rounds'] += 1
        if result == 'win':
            self['wins'] += 1
        elif result == 'loss':
            self['losses'] += 1
        else:
            self['draws'] += 1

    def add2score(self):
        """Adds the scores from the game to total scores"""
        self['games_played'] += 1
        self['rounds_lost'] += self['losses']
        self['rounds_won'] += self['wins']
        self['rounds_tied'] += self['draws']
        self['total_rounds'] += self['rounds']
        if self['losses'] > self['wins']:
            self['games_lost'] += 1
        elif self['losses'] < self['wins']:
            self['games_won'] += 1
        else:
            self['game_draws'] += 1

    def stats_board(self):
        """Returns the stat board"""
        return ('\n\n++++++++++++++++++++-=Stats=-++++++++++++++++++++++\n'
                '===================================================\n'
                '|--{:^11}--|--{:^12}--|--{:^12}--|\n'.format("X   ", "Rounds", "Games") +
                '|--{:^11}--|--{:^12}--|--{:^12}--|\n'.format("Wins  ", self['rounds_won'], self['games_won']) +
                '|--{:^11}--|--{:^12}--|--{:^12}--|\n'.format("Losses", self['rounds_lost'], self['games_lost']) +
                '|--{:^11}--|--{:^12}--|--{:^12}--|\n'.format("Draws ", self['rounds_tied'], self['game_draws']) +
                '|--{:^11}--|--{:^12}--|--{:^12}--|\n'.format("Played", self['total_rounds'], self['games_played']) +
                '\n')

    def final_score(self):
        """Returns the games final board"""
        return ('\n\n+++++++++++Final Score++++++++++++\n'
                '==================================\n'
                '|--{:^11}--|--{:^12}--|\n'.format('Wins  ', self['wins']) +
                '|--{:^11}--|--{:^12}--|\n'.format('Losses', self['losses']) +
                '|--{:^11}--|--{:^12}--|\n'.format('Draws  ', self['draws']) +
                '|--{:^11}--|--{:^12}--|\n'.format('Rounds', self['rounds']) +
                '\n')


class Game:
    """Main Game Class"""
    MOVES = ('rock', 'paper', 'scissors')
    ROUND_OPTIONS = ('1', '3', '5', '7')
    MENU = ('stats', 'play', 'quit')
    WIN_CONDITIONS = {
        "rock": "scissors",
        "scissors": "paper",
        "paper": "rock",
    }
    green = colorama.Fore.GREEN
    yellow = colorama.Fore.YELLOW
    cyan = colorama.Fore.CYAN
    blue = colorama.Fore.BLUE
    magenta = colorama.Fore.MAGENTA
    COLORS = (green, yellow, cyan, blue, magenta)

    def delirioussyntax(self):
        """Creator"""
        colorama.init()
        idle = "idlelib" in sys.modules
        time.sleep(.3)
        if idle is False:
            print(colorama.Back.BLACK + colorama.Style.BRIGHT, end='')
        for letter in "Delirious":
            if idle is False:
                print(random.choice(Game.COLORS), end='')
            print(letter, end='')
            sys.stdout.flush()
            time.sleep(random.uniform(.1, .4))
        if idle is False:
            print(colorama.Fore.RED, end='')
        for letter in "Syntax":
            print(letter, end='')
            sys.stdout.flush()
            time.sleep(random.uniform(.1, .4))
        print(colorama.Style.RESET_ALL, "\n\n")

    def intro(self):
        """Intro statements"""
        self.Score = Scorecard()
        try:
            with shelve.open("RPSv2.dat") as f:
                self.Score = f["statistics"]
        except KeyError:
            with shelve.open("RPSv2.dat") as f:
                f["statistics"] = self.Score

        print("Brought to you by: ", end='')
        sys.stdout.flush()
        self.delirioussyntax()
        time.sleep(1)
        print("Welcome to the greatest, mind blowing challenge of all time.")
        print("     - Rock, Paper, Scissors!\n")
        print("Many have tried and many have FAILED...")
        print("This will be a test between the human mind and my AI.")
        input("Press \"enter\" when you believe your ready for this challenge.\n")
        print("\nGood Luck... Human.\n\n")

    def custom_input(self, question, choices):
        """A custom loop that checks to see if choices are valid
        :param choices:
        :param question:
        """
        response = None
        while True:
            while response not in choices:
                response = input(question).lower()
                if response in choices:
                    return response
                print("Correct inputs:\n  >", end='')
                print("\n  >".join(choices), "\n")

    def start_game(self):
        """Main menu of game basically"""
        self.intro()
        while True:
            choice = self.custom_input("Would you like to play, look at stats, or quit?:\n   ->", self.MENU)
            if choice == 'play':
                self.play_game()
            elif choice == 'stats':
                stats = self.Score.stats_board()
                print(stats)
            else:
                break

    def computer_choice_gen(self):
        """Generates computer choice"""
        return random.choice(Game.MOVES)

    def play_game(self):
        """Player vs Computer game"""
        rounds = int(self.custom_input("\nHow many rounds would you like to play?\n   ->", self.ROUND_OPTIONS))
        while self.Score['rounds'] != rounds:
            self.user_choice = self.custom_input("\nWhat is your choice, human?\n   ->", self.MOVES)
            self.computer_choice = self.computer_choice_gen()
            print("\nComputer choice is {}".format(self.computer_choice))
            result = self.evaluate()
            self.Score.round_update(result)
            if result == "win":
                print("{} beats {}! The human wins this round.\n\n".format(self.user_choice, self.computer_choice))
            elif result == "loss":
                print("{} beats {}! Hahaha! You lost this round!\n\n".format(self.computer_choice, self.user_choice))
            else:
                print("I knew you were going to pick {}!\n\n".format(self.user_choice))
        print(self.Score.final_score())
        self.Score.add2score()
        self.Score.reset()
        with shelve.open("RPSv2.dat") as f:
            f["statistics"] = self.Score

    def evaluate(self):
        """returns if outcome of round"""
        if Game.WIN_CONDITIONS[self.user_choice] == self.computer_choice:
            return "win"
        elif self.user_choice == self.computer_choice:
            return "draw"
        else:
            return "loss"


if __name__ == "__main__":
    Game = Game()
    Game.start_game()
EN

回答 1

Code Review用户

回答已采纳

发布于 2015-11-16 09:47:11

很高兴看到来自第一个问题的建议有所帮助!我只是有一些小小的笔记。

到处都有文档字符串很好,但是您可以对文档字符串使用''',这比避免双引号更容易阅读。

代码语言:javascript
运行
复制
'''Stores all items related to "Score"'''

说到博士

代码语言:javascript
运行
复制
def delirioussyntax(self):
    """Creator"""

这真的不清楚它是做什么的。如果它是作为一个复活节彩蛋,那么它是有趣的混淆,调用该功能,并看到它运行。但既然你叫它,那它就不是真的隐藏了。给它一个更清晰的名称或一个文档字符串,它实际上概述了它所做的事情。

代码语言:javascript
运行
复制
def print_creator_name(self):

custom_input中,您有两个while循环,但实际上只需要while True循环。您有一个return语句,所以只要那里有一个有效的输入,您的函数就会返回并结束循环。没有其他时间循环应该结束,所以您可以无限期地循环:

代码语言:javascript
运行
复制
def custom_input(self, question, choices):
    """A custom loop that checks to see if choices are valid
    :param choices:
    :param question:
    """

    while True:
        response = input(question).lower()
        if response in choices:
            return response
        print("Correct inputs:\n  >", end='')
        print("\n  >".join(choices), "\n")

尽管您只增加了一个,但我个人认为,在play_game中使用更少的测试比使用更少的测试更好。对大脑来说,当你玩的回合比整盘少的时候,你想要跑的话就更符合逻辑了。但是,如果你认为你是在玩游戏,而你玩的数量并不等于选择的数量,那就更让人困惑了。这也是避免潜在错误的一种方法,如果循环数量增加超过1,您可能会忘记更新它,并且意外地创建了一个无限循环。

代码语言:javascript
运行
复制
    while self.Score['rounds'] < rounds:
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/110586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档