Камень, ножницы, бумага Спок, ящерица, питон с модулем алгоритма - PullRequest
0 голосов
/ 02 декабря 2018

В настоящее время я новичок в python и мире программирования, поэтому этот вопрос может показаться вам очень новым.

Я пытаюсь создать игру «Камень, бумага, ножницы, ящерица и Спок».Я хотел использовать по модулю, чтобы сохранить много операторов if.Моя проблема в том, что я не могу по модулю определить правильного победителя.Кто-нибудь может увидеть, что я делаю не так?

import random

while True:
    User1 = input('What s your name?>>>')
    print("Lets start a single player mode of rock, paper, scissors, lizard and Spock", end='.')
    print('\n choose one of the options below', User1,
          '(number only):''\n 0.rock \n 1.paper \n 2.scissors \n 3.lizard \n 4.Spock')
    player_num = int(input())
    computer_num = random.randrange(0, 5)
    difference = (player_num - computer_num) % 5
    if player_num == -5:
        winner = 'You lost'
    else:
        if difference == 0:
            winner = 'It´s a tie'
            print(computer_num)
        elif difference == 1 or difference == 2:
            winner = (User1 + "wins!")
            print(computer_num)
        elif difference == 3 or difference == 4:
            winner = 'Computer wins.'
            print(computer_num)
        else:
            print("Please select one of the options followed by 1, 2, 3 or 4.")
    print(winner)

Например, когда я ввожу 2, компьютер выбирает 3 и выигрывает игру.

1 Ответ

0 голосов
/ 02 декабря 2018

Я бы предложил добавить в функцию функцию «получить число от пользователя» и добавить некоторую обработку исключений для немых игроков:

import random

def get_numeric_input(text,num_range):
    i = -1
    while i < 0:
        k = input(text)
        try:
            i = int(k)
            if i in num_range:
                return i
            else:
                i = -1
                raise ValueError
        except ValueError:
            print("Only numbers in range: ",list(num_range))

Подробнее об этом вы можете узнать в ответах на Задать вопроспользователь для ввода, пока он не даст действительный ответ .

Вы должны только один раз спросить у пользователя его имя, поместить оставшуюся игровую логику в while с подходящей кодировкой, чтобы оставить его- Я выбираю 5 раз, достаточно проиграть.

Собирайте выигрыши / ничьи / поражения в переменные.Я добавил словарь для нумерации в отображение выбора и немного string.format () для лучшего вывода - см .:


User1 = input('What s your name?>>>')

print("Lets start a single player mode of rock, paper, scissors, lizard and Spock.")
lost = 0
win = 0
tie= 0

# dictionary lookup for nicer outputs - maps number to text
d = { 0:"rock", 1:"paper", 2:"scissors", 3:"lizard", 4:"Spock"}

# define some texts once if they repeat all the time
rules = ('''
Choose one of the options below {} - use number only:
    0. rock 
    1. paper
    2. scissors
    3. lizard
    4. Spock
Your choice? ''')
userwins = User1 + " wins!" 

while lost < 5:

    # fully automatic play - use the commented instead for human players
    player_num = random.randrange(0, 5) # get_numeric_input(rules,range(5))
    computer_num = random.randrange(0, 5)

    # always print what was choosen
    print("You took {} - the computer choose {}.".format(d[player_num], d[computer_num]), 
          end=" " )

    difference = (player_num - computer_num) % 5
    if difference == 0:
        tie += 1
        print('It´s a tie') 
    elif difference in (1,2):
        win += 1
        print(userwins)
    else:
        lost += 1
        print('Computer wins.')

print("You won {} and lost {} times. You tied {} times. Overall you are the {}.".format(
    win, lost, tie, "Winner" if win > lost else "Looser" )) 

Для реальной логики игры - ваше отображение, кажется, неверно.Правила игры гласят:

def did_I_win(me,pc):
    # 0 rock     = scissor, lizard
    # 1 paper    = rock, spock
    # 2 scissor  = lizard, paper
    # 3 lizard   = paper, spock
    # 4 spock    = rock, scissor
    wins = {0:{2,3}, 1:{0,4},2:{1,3},3:{1,4},4:{0,2}}
    return pc in wins[me]

Так что если вы измените основную программу на:

while lost < 5:

    # fully automatic play - use the commented instead for human players
    player_num = random.randrange(0, 5) # get_numeric_input(rules,range(5))
    computer_num = random.randrange(0, 5)

    # always print what was choosen
    print("You took {} - the computer choose {}.".format(d[player_num], d[computer_num]), 
          end=" " )

    difference = (player_num - computer_num) % 5
    if player_num == computer_num:
        tie += 1
        print('It´s a tie') 
    elif did_I_win(player_num,computer_num):
        win += 1
        print(userwins)
    else:
        lost += 1
        print('Computer wins.')

print("You won {} and lost {} times. You tied {} times. Overall you are the {}.".format(
    win, lost, tie, "Winner" if win > lost else "Looser" )) 

, она будет работать, как и ожидалось:

What s your name?>>>Joe
Lets start a single player mode of rock, paper, scissors, lizard and Spock.
You took Spock - the computer choose rock. Joe wins!
You took rock - the computer choose Spock. Computer wins.
You took paper - the computer choose scissors. Computer wins.
You took paper - the computer choose paper. It´s a tie
You took paper - the computer choose lizard. Computer wins.
You took rock - the computer choose Spock. Computer wins.
You took rock - the computer choose Spock. Computer wins.
You won 1 and lost 5 times. You tied 1 times. Overall you are the Looser. 

Ваша текущая логика дает вам:

                                           Result   ok? 
rock       vs paper      = (0-1) % 5 = 4   lost     ok
rock       vs scissors   = (0-2) % 5 = 3   win      ok
rock       vs lizard     = (0-3) % 5 = 2   win      ok
rock       vs Spock      = (0-4) % 5 = 1   lost     ok
paper      vs rock       = (1-0) % 5 = 1   win      ok
paper      vs scissors   = (1-2) % 5 = 4   lost     ok
paper      vs lizard     = (1-3) % 5 = 3   lost     no: earlier 3 was win
paper      vs Spock      = (1-4) % 5 = 2   win      ok
scissors   vs rock       = (2-0) % 5 = 2   lost     no: earlier 2 was win
scissors   vs paper      = (2-1) % 5 = 1   ... etc ...
scissors   vs lizard     = (2-3) % 5 = 4
scissors   vs Spock      = (2-4) % 5 = 3
lizard     vs rock       = (3-0) % 5 = 3
lizard     vs paper      = (3-1) % 5 = 2
lizard     vs scissors   = (3-2) % 5 = 1
lizard     vs Spock      = (3-4) % 5 = 4
Spock      vs rock       = (4-0) % 5 = 4
Spock      vs paper      = (4-1) % 5 = 3
Spock      vs scissors   = (4-2) % 5 = 2

Программа:

d= { 0:"rock",1:"paper",2:"scissors",3:"lizard",4:"Spock"}

# rock = scissor, lizard
# paper = rock, spock
# scissor = lizard, paper
# lizard= paper, spock
# spock = rock, scissor
print("------")
for i in range(5):
    for j in range(5):
        if i!=j: 
            print("{:<10} vs {:<10} = ({}-{}) % 5 = {}".format(
                d[i],d[j],i,j,(i-j)%5))
...