0

我必须编写一个类似于石头剪刀布的程序游戏,但有五个选项而不是三个选项。我能够使用 ifs 系统编写代码,但我想知道是否有更好的方法来编写代码。

游戏规则:

如您所见,共有 5 个选项(X → Y 表示 X 胜过 Y):

  1. 摇滚 → 蜥蜴和剪刀
  2. 纸→摇滚和斯波克
  3. 剪刀→纸和蜥蜴
  4. 蜥蜴 → Spock & Paper
  5. 斯波克 → 剪刀和石头

主要代码:

import random
from ex2_rpsls_helper import get_selection

def rpsls_game():
  com_score = 0
  player_score = 0
  draws = 0
  while(abs(com_score - player_score) < 2):
    print("    Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")
    selection = int(input())
    # a while loop to make sure input i between 0<x<6
    while(selection <= 0 or selection > 5):
        print(    "Please select one of the available options.\n")
        selection = int(input())
    com_selection = random.randint(1,5)
    print("    Player has selected: "+get_selection(selection)+".")
    print("    Computer has selected: "+get_selection(com_selection)+".")

    # A set of else and elseif to determin who is the winner
    if(give_winner(selection, com_selection)):
        print("    The winner for this round is: Player\n")
        player_score += 1
    elif(give_winner(com_selection,selection)):
        print("    The winner for this round is: Computer\n")
        com_score += 1
    else:
        print("    This round was drawn\n")
        draws += 1

    print("Game score: Player "+str(player_score)+", Computer "+str(com_score)+", draws "+str(draws))
  if(player_score > com_score):
    return 1
  else:
    return -1

IFS系统:

def give_winner(first_selection, second_selection):
    if(first_selection is 1):
        if(second_selection is 3 or second_selection is 4):
            return True
    elif(first_selection is 2):
        if(second_selection is 1 or second_selection is 5):
            return True
    elif(first_selection is 3):
        if(second_selection is 2 or second_selection is 4):
            return True
    elif(first_selection is 4):
        if(second_selection is 2 or  second_selection is 5):
            return True
    elif(first_selection is 5):
        if(second_selection is 3 or second_selection is 1):
            return True
    return False

有任何想法吗?

4

6 回答 6

4

if你可以有一个(first, second)元组列表或字典,而不是一系列复杂的语句,

a = [(1,3), (1,4), (2,1), (2,5) ...]

def give_winner(first_selection, second_selection):
    return (first_selection, second_selection) in a

您还可以使用 afrozenset来提高性能。

于 2013-10-25T08:02:06.587 回答
3

你可以用字典。

dictionary = {
    1: [3, 4],
    2: [1, 5],
    3: [2, 4],
    4: [2, 5],
    5: [3, 1]
}

def give_winner(first_selection, second_selection):
    if dictionary.has_key(first_selection):
        if second_selection in dictionary[first_selection]:
            return True
    return False
于 2013-10-25T08:05:37.027 回答
0

也给获胜者选择:

def give_winner(first_selection, second_selection):
    rules = {
        1: lambda x: x in (3, 4),
        2: lambda x: x in (1, 5),
        3: lambda x: x in (2, 4),
        4: lambda x: x in (2, 5),
        5: lambda x: x in (3, 1)
    }
    return rules[first_selection](second_selection)
于 2013-10-25T08:05:11.983 回答
0

我喜欢构建自己的小版本的石头剪刀布蜥蜴 Spock。

您通过解释 som 规则开始了您的帖子。所以我想,为什么不将规则合并到代码中。而且我想使用真实的单词而不是数字,因为这样更容易理解。但我同意每次都正确拼写剪刀会很麻烦,所以我希望数字也可以作为输入。

from random import randint

# ex. scissors and lizard is beaten by rock
beaten_by = {'rock': ['scissors', 'lizard'],
             'paper': ['rock', 'spock'],
             'scissors': ['paper', 'lizard'],
             'lizard': ['spock', 'paper'],
             'spock': ['scissors', 'rock']}

def rplsls_game():
    player_score, computer_score = 0, 0
    weapons = ['rock', 'paper', 'scissors', 'lizard', 'spock']

    while(abs(player_score - computer_score) < 2):

        print "-----------------------------------------------------------"
        print " Please enter your selection: "
        print " 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock)"

        computer_weapon = weapons[randint(0, 4)]
        weapon = raw_input()
        if weapon in '12345': weapon = weapons[int(weapon) - 1]
        if weapon not in weapons:
            print "invalid input"
            continue        
        print "You selected: " + weapon
        print "Computer selected: " + computer_weapon

        if computer_weapon in beaten_by[weapon]:
            print "You won!"
            player_score += 1
        elif weapon in beaten_by[computer_weapon]:
            print "Computer won!"
            computer_score += 1
        else:
            print "Draw!"

        print "Player: " + str(player_score)
        print "Computer: " + str(computer_score)

    if player_score > computer_score:
        print "Congratulations! you won the game"
    else:
        print "Computer won the game..."

rplsls_game()
于 2013-10-25T14:09:02.667 回答
0

您可以在 python 中使用类。例如,您可以将播放器作为具有以下属性的类:-

    Score
    Name
    OptionChosen

等类似地,您可以制作类似的方法

    UpdateScore()
    DeclareWinner()

等等。这样你的程序会感觉更“整洁”。您还可以创建一个 main() 函数,其中包含一个

    while True:

并将您的所有内容放在那里。例如

    class Player:
        def __init__(self,name, score = 0):
          self.name = name
          self.score = score  # initially score is zero
        def ChooseOption(self, name):
           if name == "computer":
            # select choice randomly code
           else:
             var = int(input("Enter choice: "))
        def UpdateScore(self):
            self.score += 1
    def main():
        player1 = Player("Name")
        player2 = Player("Computer") 
        while True:
         resp1 = player1.ChooseOption()
         resp2 = player2.ChooseOption()
         # add other code to manipulate resp1 and resp2 here 

同样你可以编写其他东西,希望这能给你一些想法

于 2013-10-25T07:58:42.120 回答
-1

您也可以使用 raw_input 实例:

print("    Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")
selection = int(input())

try:
  selection = input("Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")
except ...

你完全忘记了例外。

如果 give_winner 函数中的词干太大,请使用字典或 lambda 函数。

于 2013-10-25T08:06:26.810 回答