2014-04-22 5 views
3

우리는 파이썬 프로그램을 만들어 크랩 게임을 시뮬레이션하고 승리 확률을 표시하려고합니다. while 루프에 대한 답을 좁히고 제목에서 알 수 있듯이 루프를 치면 종료하지 않습니다. 지금까지 루프가 끝나야한다고 말할 수는 있지만 대신에 "거짓"의 끝없는 열차가 돌아옵니다. 다음은 전체 프로그램에 대한 주석이있는 코드입니다. 맨 아래에는 크랩에 대한 규칙을 입력 해 보겠습니다. while 루프가 파이썬에서 멈추지 않습니다

import random 
def craps() 
    roll = random.randint(1,6) + random.randint(1,6) 
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter 
    return 1 
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0 
    return 0 
else: 
    roll2 = 0 #initializes roll2 for the while 
    while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll 
     roll2 == random.randint(1,6) + random.randint(1,6) #Rolls the dice 
     if (roll2 == roll): #Tests if the player should win 
      return 1 
     elif (roll2 == 7): #Tests if the player should lose 
      return 0 

win = 0 #Start the win counter at 0 
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played 
for i in range (games): 
    win = win + craps() #adds a 1 or a 0 depending on if a game was won 

print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning 

우리가 사용하는 기본적인 규칙

은 : 초기 롤 7 또는 11 플레이어 승 (라인 4) 인 경우, 플레이어가 2 여섯 개면 주사위를 굴린다. 플레이어가 2, 3 또는 12를 굴리는 경우 플레이어는 잃습니다 (6 행). 플레이어가 초기 롤 또는 롤에 일치 할 때까지 롤링을 유지합니다. 7. 초기 롤과 일치하면 승리합니다. 그들은 7 점을 잃습니다 (10-15 행). 우리의 프로그램은 선수가이기는 확률을 시뮬레이션하고 표시하기로되어 있습니다.

나는이 사이트를 처음 사용하기 때문에 앞으로 어떤 일을 망쳤는지 알려주십시오. 도와 줘서 고마워!

+0

아마도 def 문 (콜론 필요)은 win = 0 행까지 확장됩니까? –

답변

3

공통적이지만 매우 실망스럽고 시간 낭비하는 오타가있어 최고의 Python 개발자도 얻을 수 있습니다. roll2 == random.randint(1,6) + random.randint(1,6)roll2 = random.randint(1,6) + random.randint(1,6)으로 대체하십시오.

또한 roll2 != roll and roll2 != 7이 필요하다고 생각합니다. 문체의 관점에서 볼 때 if 또는 while 행으로 평가 된 명령문을 괄호로 묶는 것이 좋습니다.

루프에는 약간의 중복성이 있습니다. 각 루프 상단 및 각 루프 끝에서 roll2roll 또는 7인지 확인합니다. 또한이 시도 고려할 수 :

while True: 
    # do everything in the same way as before 

또는

while roll2 != roll and roll2 != 7: 
    # do stuff with the roll 
    roll = random.randint(1,6) + random.randint(1,6) 
return 1 if roll2 == roll else return 0 # a "ternary operator" in Python 
+0

오, 그걸로 ... 나는 내가 구문 오류를 위아래로 확인했다고 생각한다고 맹세한다. 고맙습니다! – user3288723

+0

실제로 컴파일 할 때 논리 오류가 발생하지만 예상대로 작동하지 않습니다. 그리고 좋은 캐치 @ SimonT에'and', 나는 그것을 본 유일한 사람이라고 생각했습니다. – Luigi

2

이중 등호는 평등에 대한 테스트를 서명합니다. 코드가 작동하도록 단일 코드로 변경하십시오. 여기

import random 
def craps() 
    roll = random.randint(1,6) + random.randint(1,6) 
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter 
    return 1 
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0 
    return 0 
else: 
    roll2 = 0 #initializes roll2 for the while 
    while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll 
     roll2 = random.randint(1,6) + random.randint(1,6) #Rolls the dice 
     if (roll2 == roll): #Tests if the player should win 
      return 1 
     elif (roll2 == 7): #Tests if the player should lose 
      return 0 

win = 0 #Start the win counter at 0 
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played 
for i in range (games): 
    win = win + craps() #adds a 1 or a 0 depending on if a game was won 

print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning 

예는 다음과 같습니다 : 여기에 편집 된 코드는

>>> import time 
>>> x = 7 
>>> x == 7 
True 
>>> while x != 6: 
...  x == 6 
...  time.sleep(1) 
... 
False 
False 
False 
^CTraceback (most recent call last): 
    File "<stdin>", line 3, in <module> 
KeyboardInterrupt 
>>> while x != 6: 
...  x = 6 
...  time.sleep(1) 
... 
>>> 
+0

감사합니다. 나는 그처럼 단순한 오류가 내게 최고가되도록 내버려 둔다. 나는 항상 평등을 확인하기 위해 두 개의 등호를 두는 것을 기억하는 데 문제가있었습니다. 이제 우연히 그것을 할당하는 데 사용하고 있습니다. – user3288723

+0

:) 아무런 문제가 없지만 15 분 후에 가장 도움이 된 답을 수락하는 것을 잊지 마시고 고맙습니다. –

1

첫 번째 문제는이 라인이다 : 롤이 아닌 경우

while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll 

이 무한 루프 될 것입니다 7. 하나를 중 하나 인 으로 변경하려는 경우 여기에서 and을 입력해야합니다. 거짓, 인 경우 모두입니다. 이해가 되니?

당신이 원하는 :

while (roll2 != roll and roll2 != 7): #as long as both are not `True` then keep rolling. 

귀하의 다른 문제는이 라인이다 :

roll2 == random.randint(1,6) + random.randint(1,6) 

더블은 ROLL2 왼쪽에 표현 동일 있는지 확인 같습니다.당신이 원하는 것은 다음과 같이 왼쪽의 표현식과 동일하게 설정됩니다 :

roll2 = random.randint(1,6) + random.randint(1,6) 
관련 문제