Избегайте повторяющегося цикла, который повторяет инструкцию каждый раз, когда она достигает конца - PullRequest
0 голосов
/ 11 сентября 2018

Моя проблема в том, что моя программа «камень, бумага, ножницы» где-то зациклена. Я подозреваю, что это либо внутренний цикл, который запрашивает у пользователя количество раундов, либо внешний цикл, который спрашивает пользователя, сколько игроков должно сыграть; у обоих могут быть проблемы с отступами, но я не уверен.

import random
from os import system, name
from time import sleep
#variable declarations and initializations
computer,players, rounds, wins, loses, draws, yourPlay, count, rec, playerRange =  0, 0, 0, 0, 0, 0, 0, 0, 0, 3

#function definitions
def RoundsWonResult():
    print ("You played:",playerMoves[yourPlay])
    print ("The computer played:",playerMoves[computer])
    print (playerMoves[yourPlay] + " beats " + playerMoves[computer] +"!")
    print ("You win!")
    return
def RoundsLostResult():
    print ("You played:",playerMoves[yourPlay])
    print ("The computer played:",playerMoves[computer])
    print (playerMoves[computer] + " beats " + playerMoves[yourPlay] +"!")
    print ("You lose!")
    return    
def DrawMatch():
    global draws
    while (yourPlay == computer):
        print ("You played:",playerMoves[yourPlay])
        print ("The computer played:",playerMoves[computer])
        print ("It's a draw!")
        draws+=1
        return
def WinsMatch():
    global wins
    while (yourPlay != computer):
        if (yourPlay == 0 and computer != 1):
            if (computer == 2):
                RoundsWonResult()
                wins+=1
        elif (yourPlay == 1 and computer == 0):
            if (computer != 2):
                RoundsWonResult()
                wins+=1
        elif (yourPlay == 2 and computer != 0):
            if (computer == 1):
                RoundsWonResult()
                wins+=1          
        return
def LosesMatch():
    global loses
    while (yourPlay != computer):
        if (yourPlay == 0 and computer == 1):
            if (computer != 2):
                RoundsLostResult()
                loses+=1
        elif (yourPlay == 1 and computer == 2):
            if (computer != 0):
                RoundsLostResult()
                loses+=1
        elif (yourPlay == 2 and computer == 0):
            if (computer != 1):
                RoundsLostResult()
                loses+=1 
        return
try:
    players = int(input("Enter number of players[1-3]:"))
    while (players < 1 or players > playerRange):
        print ("Invalid range selected!")
        players = int(input("Enter number of players[1-3]:"))
except ValueError:
        print ("Only numeric values are allowed!")
        players = int(input("Enter number of players[1-3]:"))        
if (players > 0 and players <= 3):
    print ("Good luck to all " + str(players) + " of you. May the better player win!")
while (rec < players):
    try:
        rounds = int (input("Enter number of rounds to play:"))
        while (rounds <= 0):
            print ("Value must be greater than zero!")
            rounds = int (input("Enter number of rounds to play:"))
            print(rec)
            print(rounds)
    except ValueError:
            print ("Only numeric values are allowed!")
            rounds = int (input("Enter number of rounds to play:"))            
            if (rounds != "" and rounds > 0):
                print ("Let the games begin!")
    else:
        print ("Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. Good Luck!")
        print("You entered " + str(rounds) + " round(s)!")
        playerMoves = ["Rock","Paper","Scissors"]
        while (count < rounds):
            try:
                yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
                while (yourPlay < 0 or yourPlay > 2):
                    print ("Invalid selection!")
                    yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
            except ValueError:
                print ("Only numeric values are allowed!")
                yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
            else:
                computer = random.randint(0,2) #randomizes the numbers  0 - 2
            if (yourPlay == computer):
                DrawMatch()
            elif (yourPlay != computer):
                WinsMatch()
                LosesMatch() 
            count+=1
            print ("End of Round ", count)
            if (count == rounds):
                print ("Wins:",wins)
                print ("Loses:",loses)
                print ("Draws:",draws) 
                #resultLog = {"Wins":wins,"Loses":loses,"Draws":draws}
                fileName = input("Enter Your name: ")
                #print (resultLog)   
                with open (fileName,"w") as plyrRec:
                    print ("Your file has been created!")
                    plyrRec.close()
                with open (fileName, "a") as plyrRec:
                    plyrRec.write ("{}{}\n{}{}\n{}{}\n".format("Wins:",wins,"Loses:",loses,"Draws:",draws))
                    plyrRec.close()
                    rec+=1
                    print ("End of Record ", rec)

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

...