首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一个简单的石头,纸,剪刀程序

一个简单的石头,纸,剪刀程序
EN

Code Review用户
提问于 2017-03-13 04:14:09
回答 3查看 6.3K关注 0票数 10

我写了一个石头,纸,剪刀程序。它工作得很好,但我很好奇,在代码的操作、执行、外观等方面,是否有任何建设性的批评、提示、技巧、评论或建议。

代码语言:javascript
复制
# This code is a PvC Rock-Paper-Scissors Game!
# Import Random Library for Computer Choice
import random

# Greeting & Introduction
print ("Hello! Let's play Rock-Paper-Scissors!");

# Just to Make things Smoother.
options = {1:'rock', 2:'paper', 3:'scissors'};
player_result = ["tie!", "win!", "lose!"];

# Obtain Player & CPU Inputs
def collection(user_choice = 42):
    # user_choice Collection
    while (user_choice not in ['1','2','3']):
        # Prompts the User for a number & Stores as raw_input
        print ("Pick a Number: \n 1) \t Rock \n 2) \t Scissors \n 3) \t Paper \n");
        user_choice = raw_input();
        # Checks to see if the choice is acceptable
        if (user_choice in ['1','2','3']):
            break;
        # If not acceptable, restart the loop (ask again).
        else:
            print("\nPlease pick either 1, 2, or 3!\n");

    # Convert user_choice to Int
    user_choice = int(user_choice);

    # choose comp_choice
    comp_choice = random.randint(1,3);
    return (user_choice, comp_choice);

# Translate Results into English
def translate_choices(user,comp):
    print ("\nYou chose " + options[user] +"!");
    print ("Computer chose " + options[comp] +"!");

# Comparison Function returns Game Results
def compare(x,y):
    result = player_result[ (x-y)%3 ];
    return result;

(user_choice,comp_choice) = collection();
translate_choices(user_choice,comp_choice);
result = compare (user_choice, comp_choice);
print ("You " + result);
EN

回答 3

Code Review用户

回答已采纳

发布于 2017-03-13 07:06:19

自上而下:

进口

由于您只使用了random中的一件东西,所以您最好只导入一件东西:

代码语言:javascript
复制
from random import randint

作为PEP8 8推荐,无论何时,只要是通过标准导入来订购您的导入,然后是第三方导入,最后是本地导入。

对Parentheses

的使用

在Python2中,print语句不需要括号。如果使用Python3,则print函数调用需要它们。其他区域(例如collections的while循环和返回语句)不需要它们周围的括号。

稍后请注意:您可以在print语句中使用逗号,以便在事物之间有空格,或者可以将两个字符串与+运算符连接起来。

代码语言:javascript
复制
>>> print "Hello", "World!"
Hello World!
>>> print "Hello" + "World!"
HelloWorld!

不过,我不会把这两者混为一谈(可能会让事情看起来很混乱),这只是一个有用的说明,说明两者之间的区别。

不必要的注释

您的许多代码已经自我记录,不需要注释(这是一件好事)。

你应该只评论一些你认为很难理解的区域,例如计算游戏结果。

如果您最终使用了函数,您可能需要添加一些有用的文档字符串来描述正在发生的事情,或者重命名该函数。

代码语言:javascript
复制
def calculate_winner(x, y):
    """<Explain how calculate_winner works here>."""
    #...etc...

代码组织

您的许多代码似乎不需要在函数中,例如translate_choicescompare。你只使用过一次,这一切都与你的游戏有关。

这是个人偏好,但将所有代码移到函数中并避免使用全局变量可能会更好。这样,如果其他人最终导入了您的代码,他们就不会遇到冲突。

代码语言:javascript
复制
def play_rps():
    # ... rest of your code here ...

另外,确保您的代码只在被调用为main时才能运行,这可能是很好的。

代码语言:javascript
复制
if __name__ == '__main__':
    play_rps()

并且通过python rps_name.py调用,或者承载代码的文件名可能是。

更多关于__main__ 这里的信息。

处理用户选择

不要每次都列一个列表,为什么不使用你已经做好的字典中的键呢?

代码语言:javascript
复制
while user_choice not in options:
    # do user_choice stuff here

此外,为了简化while循环中的逻辑,只需检查无效的输入,就可以删除make语句:

代码语言:javascript
复制
while user_choice not in options:
    #...print prompt for user choice here...
    user_choice = raw_input()

    if user_choice not in options:
        print '\nPlease pick either 1, 2, or 3!\n'

最后,还可以将raw_input的后一次转换为整数合并到while循环中:

代码语言:javascript
复制
try:
    user_choice = int(raw_input())
except ValueError:
    # input was not a valid integer
    user_choice = None

if user_choice not in options:
    print '\nPlease pick either 1, 2, or 3!\n'

不必要的分号

你来自C++/Java背景吗?我之所以问这个问题,是因为您的代码中似乎有很多分号(python不需要这些分号)。

最终产品

有了上面列出的建议(还有一些小的事情,比如拆分选项提示符),下面是我想出的代码:

代码语言:javascript
复制
from random import randint

def play_rps():
    print "Hello! Let\'s play Rock-Paper-Scissors!\n"

    options = {1:"rock", 2:"paper", 3:"scissors"}
    player_result = ["tie", "win", "lose"]

    user_choice = None

    # get user choice
    while user_choice not in options:
        print "Game options:"
        print "-------------"
        print "1) Rock"
        print "2) Scissors"
        print "3) Paper"

        try:
            user_choice = int(raw_input("Your choice: "))
        except ValueError:
            # input was not a valid integer
            user_choice = None

        if user_choice not in options:
            print "\nPlease pick either 1, 2, or 3!\n"

    # calculate computer choice
    computer_choice = randint(1, 3)

    print "\nYou chose: " + options[user_choice] + "!"
    print 'Computer chose: ' + options[computer_choice] + "!"

    # calculate winner
    result = player_result[ (user_choice-computer_choice) % 3]
    print 'You ' + result + '!'

if __name__ == '__main__':
    run_game = play_rps()

注意:使用上述格式,创建循环(如果您选择一个重放选项)也会容易得多。

票数 13
EN

Code Review用户

发布于 2017-03-13 06:46:33

一般来说,这段代码看起来相当不错。我只有几个小小的评论。

Pep8:

Python对代码的样式有很强的了解,它是用pep8表示的。

我建议你买个样式/棉线检查器。我使用吡咯烷酮,它将显示编辑器中的样式和编译问题。

不需要的else:

如果:

代码语言:javascript
复制
# Checks to see if the choice is acceptable
if (user_choice in ['1','2','3']):
    break;
# If not acceptable, restart the loop (ask again).
else:
    print("\nPlease pick either 1, 2, or 3!\n");

...could be:

代码语言:javascript
复制
# Checks to see if the choice is acceptable
if (user_choice in ['1','2','3']):
    break

# If not acceptable, restart the loop (ask again).
print("\nPlease pick either 1, 2, or 3!\n")

因为休息意味着不需要其他的。

票数 5
EN

Code Review用户

发布于 2017-03-13 14:05:46

除了这里的其他很好的反馈,我建议将用户输入提取到一个单独的函数中。这部分代码是不平凡的,它的复杂性掩盖了游戏代码.

所以我建议一个函数,比如:

代码语言:javascript
复制
OPTIONS = {1: "rock", 2: "paper", 3: "scissors"}


def get_user_move():
    """Ask the user for a move until receiving valid input"""
    while True:
        # Prompts the User for a number & Stores as raw_input
        print("Pick a Number:")
        for possible_move in OPTIONS.items():
            print(" %s) \t %s" % possible_move)

        user_choice = raw_input()
        try:
            # If the choice is acceptable, we're done
            if (int(user_choice) in OPTIONS):
                return int(user_choice)
        except ValueError:
            # Catch inputs that cannot be converted to an int
            pass
        # Keep asking again
        print("\nThe choice '%s' is invalid" % user_choice)

...

还请注意,现在选项dict在多个函数中使用;约定是使其成为模块级常量。

票数 0
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

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

复制
相关文章

相似问题

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