가위바위보 AI 이슈 (Rock paper scissors AI issue)


문제 설명

가위바위보 AI 이슈 (Rock paper scissors AI issue)

간단한 가위바위보 게임을 만들고 있습니다. comp_count가 3에 도달할 때 게임이 중지되지 않는다는 사실을 제외하고는 잘 작동합니다. player_count에 대해 잘 작동하기 때문에 이유를 이해할 수 없는 것 같습니다. 도와주세요!

from random import randint

player_count = 0
comp_count = 0

def game():
    player_choice = raw_input('Do you choose rock [r], paper [p], or scissors [s]? ')

    computer_choice = randint(0,2)
    #Rock = 0 Paper = 1 Scissors = 2

    #Player chooses paper, computer chooses rock
    if player_choice == "p" and computer_choice == 0:
        print 'Computer chose rock'
        player_won()

    #Player chooses rock, computer chooses scissors
    elif player_choice == 'r' and computer_choice == 2:
        print 'Computer chose scissors'
        player_won()

    #Player chooses scissors, computer chooses paper
    elif player_choice == 's' and computer_choice == 1:
        print 'Computer chose paper'
        player_won()

    #Computer chooses paper, player chooses rock
    elif player_choice == 'r' and computer_choice == 1:
        print 'Computer chose paper'
        computer_won()

    #Computer chooses rock, player chooses scissors
    elif player_choice == 's' and computer_choice == 0:
        print 'Computer chose rock'
        computer_won()

    #Computer chooses scissors, player chooses paper
    elif player_choice == 'p' and computer_choice == 2:
        print 'Computer chose scissors'
        computer_won()

    #Ties
    elif player_choice == 'r' and computer_choice == 0:
        print "It's a tie!"
        game()

    elif player_choice == 's' and computer_choice == 2:
        print "It's a tie!"
        game()

    elif player_choice == 'p' and computer_choice == 1:
        print "It's a tie!"
        game()

    #Wrong input
    else:
        print 'Please try again.'
        game()

def player_won():
    global player_count
    print 'You win!'
    player_count += 1
    print 'You have ' + str(player_count) + ' point(s).'
    while player_count < 3:
        game()

def computer_won():
    global comp_count
    print 'Computer wins!'
    comp_count += 1
    print 'Computer has ' + str(comp_count) + ' point(s).'
    while comp_count < 3:
        game()

print 'Welcome to Rock, Paper, Scissors! First to 3 points wins it all.'
game()

참조 솔루션

방법 1:

Your while loops are whats causing your problem. Simply change while to a if in your player_won and computer_won functions and it fixes the issue.

def player_won():
    global player_count
    print 'You win!'
    player_count += 1
    print 'You have ' + str(player_count) + ' point(s).'
    if player_count < 3:
        game()

def computer_won():
    global comp_count
    print 'Computer wins!'
    comp_count += 1
    print 'Computer has ' + str(comp_count) + ' point(s).'
    if comp_count < 3:
        game()

Now go rock paper scissors your heart out!

방법 2:

I admit this isn't really a direct answer to your question, but I feel it might be useful to have a potentially simpler way to write this brought up.

You could make the user choose from three different numbers in the input instead of letters, or just convert the letters to numbers. One advantage of this is that to test for a tie, you could simply write:

if player_choice == computer_choice:

Even checking for who won in a game if it wasn't a tie wouldn't be very difficult, since if it is all numeric, an option that beats another one will be one away from it in a certain direction. So, for example, you could test if the player won like so:

winning = computer_choice ‑ 1
if winning == ‑1: winning = 2
if player_choice == wining:
    player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
    computer_won()

If each number represented a different option (for example if you had a dictionary linking 0 to rock, 1 to scissors, and 2 to paper), then this would check if the user chose the option before the computer's, which would be the winning option.

That would actually let you check for who won and with which options with relatively few if statements. Your check could look something like this:

options = {0: "rock", 1:"scissors", 2:"paper"}

#collect player and computer choice here

print "computer chose "+options[computer_choice] #We will probably tell them what the computer chose no matter what the outcome, so might as well just put it once up here now that a variable can determine what the computer chose.

if player_choice == computer_choice:
    print "It's a tie!"
    game()

winning = computer_choice ‑ 1
if winning == ‑1: winning = 2

if player_choice == wining:
    player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
    computer_won()

This isn't really necessary for making your code work, but I think it will be useful if you are interested.

(by HautchRyantrevorKirkby)

참조 문서

  1. Rock paper scissors AI issue (CC BY‑SA 2.5/3.0/4.0)

#Python #Artificial-Intelligence






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트