0

My problem is, my rock, paper, scissors program seems trapped in a loop somewhere. I suspect it's either the inner loop that asks the user for the number of rounds, or the outer loop that asks the user how many players should play; both might even have indentation problems but I am not sure.

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)

So the code works fairly well except that at the end of the first round it repeatedly asks the user to enter number of rounds to play. I hope someone can advise me please.

2
  • Whats the value of rec and players when the the player is asked to enter number of rounds to play? Your problem may be due to this line: while (rec < players): Commented Sep 11, 2018 at 1:37
  • 2
    Please cut out the useless "junk" and provide a minimal reproducible example to maximize your chances of getting an answer... Few people are willing to debug through 100s of lines for you... Commented Sep 11, 2018 at 1:51

1 Answer 1

1
#Date first created: September 6, 2018 v.0
#Version: v.1, modified 2021/08/31
#This is a Rock, Paper, Scissors game. 
#Rock beats scissors, scissors beats paper, and paper beats rock.

import random

#variable declaration and initialization
game_moves = ["Rock","Paper","Scissors"]

def is_input_numeric(str_val):
    '''(string) -> bool
    Returns whether a string input contains ONLY numeric values greater than zero
    >>> is_input_numeric('4')
    True
    >>> is_input_numeric("like 7")
    False  
    '''
    return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20

def is_input_numeric_range(str_val):
    '''(string) -> bool
    Returns whether a string input contains ONLY a numeric value greater than zero but less than
    or equal to two
    >>> is_input_numeric_range('y')
    False
    >>> is_input_numeric_range('3')
    False
    >>> is_input_numeric_range('2')
    True
    '''
    return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2
            

def validate_rounds():
    '''(string) -> string
    checks str_val and passes control to is_input_numeric function, then returns a string value
    >>> validate_rounds() -> is_input_numeric("time")
    False
    >>> validate_rounds() -> is_input_numeric('0')
    False
     >>> validate_rounds()-> is_input_numeric('10')
     True
    '''
    valid_rounds = False
    while not valid_rounds:
        rounds = input("Enter number of rounds to play[min = 1, max = 20]: ")
        valid_rounds = is_input_numeric(rounds)
    return rounds
     
def validate_player_input():
    '''(string) -> string
    checks string and passes control to is_input_numeric_range function, then returns the string value
    >>> validate_player_input() -> is_input_numeric_range('-1')
    False
    >>> validate_player_input() -> is_input_numeric_range('i')
    False
    >>> validate_player_input() -> is_input_numeric_range('3')
    False
    >>> validate_player_input() -> is_input_numeric_range('0')
    True
    '''
    valid_player_control = False
    while not valid_player_control:
        player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ")
        valid_player_control = is_input_numeric_range(player_move)
    return player_move

def get_computer_play():
    '''Returns a whole number in the range 0:2
    '''
    computer_move = random.randint(0,2)
    return computer_move
    

def human_player_wins(plyr, comp):
    wins = 0
    rock_beats_scissors = False
    paper_beats_rock = False
    scissors_beats_paper = False
    human_hand = plyr
    computer_hand = comp
    if human_hand == 0 and computer_hand == 2:
        rock_beats_scissors = True
    elif human_hand == 1 and computer_hand == 0:
        paper_beats_rock = True
    elif human_hand == 2 and computer_hand == 1:
        scissors_beats_paper = True
    if rock_beats_scissors  or paper_beats_rock or scissors_beats_paper:
        print(game_moves[human_hand] +  " beats " + game_moves[computer_hand] + "!")
        print("You Win!")
        wins += 1
    return wins

                
def human_player_lose(plyr, comp):
    lose = 0
    rock_beats_scissors = False
    paper_beats_rock = False
    scissors_beats_paper = False
    human_hand = plyr
    computer_hand = comp
    if human_hand == 0 and computer_hand == 1:
        paper_beats_rock = True
    elif human_hand == 1 and computer_hand == 2:
        scissors_beats_paper = True
    elif human_hand == 2 and computer_hand == 0:
        rock_beats_scissors = True
    if rock_beats_scissors  or paper_beats_rock or scissors_beats_paper:
        print(game_moves[computer_hand] +  " beats " + game_moves[human_hand] + "!")
        print("You Lose!")
        lose += 1
    return lose

    
def players_draw():
    draws = 0
    print("It's a draw!")
    draws += 1
    return draws
    

def start_game():
    rounds_played = 0
    total_wins = 0
    total_losses = 0
    total_draws = 0
    highest_score = 0

    game_rounds = input("Enter number of rounds to play[Max = 20]: ")
    rounds_valid = is_input_numeric(game_rounds)
    if not rounds_valid:
        game_rounds = validate_rounds()
        
    while rounds_played < int(game_rounds):
        player_hand = input("(0)Rock,(1)Paper,(2)Scissors: ")
        valid_control  = is_input_numeric_range(player_hand)
        print('plyr:', player_hand)
        if not valid_control:
            player_hand = validate_player_input()
        computer_hand = get_computer_play()
        print('comp:', computer_hand)
        if int(player_hand) == computer_hand:
            total_draws += players_draw()
        if int(player_hand) != computer_hand:
            total_wins += human_player_wins(int(player_hand),computer_hand)
            total_losses += human_player_lose(int(player_hand),computer_hand)
        rounds_played += 1
        
    if total_wins > highest_score:
        highest_score = total_wins * 10
    print('\n--------------------------GAME RESULTS--------------------------')
    print('\nHigh Score = ', highest_score )
    print('\nrounds played = ', rounds_played, '||','wins = ', total_wins,'||', 'losses = ', total_losses, '||','draws = ', total_draws )
    print('\n--------------------------END OF RESULTS------------------------')
     
    

start_game()

            

Thanks to those who tried to helped me it was appreciated. This is the new version now after four years. Yikes!

Sign up to request clarification or add additional context in comments.

1 Comment

Consider marking this answer as correct by pressing the checkmark. Also, it would be helpful for others if you describe the exact solution, next to the new code version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.