Home > OS >  loop while and look of the program in python
loop while and look of the program in python

Time:11-08

I am writing a program rock-paper-scissors and I have a problem with a loop while which I solved with another loop if but I still wonder why it doesn't work(line 19, 71, 104; or just in functions game, game2, game3). I also want to ask if I can write this program better or use something more advance to write it shorter. Here is the code:

import random
import time

option = ["rock", "paper", "scissors"]
your_score = 0
computer_score = 0

#functions  

def game(your_score, computer_score):
    print("ok, lets start")
    time.sleep(1)
    print(3)
    time.sleep(1)
    print(2)
    time.sleep(1)
    print(1)
    time.sleep(1)
    while your_score != 1 or computer_score != 1:
        if your_score == 2 or computer_score == 2:
            break
        user = int(input("What do you shoot?\n1.rock\n2.paper\n3.scissors\n"))
        computer = random.choice([1, 2, 3])
        show(user, computer)
        
        if user == computer:
            print("it's a tie\n")

        elif is_win(user, computer):
            print("you won\n")
            your_score  = 1

        else:
            print("you lost\n")
            computer_score  = 1
    
    if your_score == 1:
        print("You won, gg")

    elif computer_score == 1:
        print("You lost, nt")

def show(user, computer):
    if user == 1:
        print(f"You: {option[0]}")

    elif user == 2:
        print(f"You: {option[1]}")

    elif user == 3:
        print(f"You: {option[2]}")

    if computer == 1:
        print(f"Computer: {option[0]}")

    elif computer == 2:
        print(f"Computer: {option[1]}")

    elif computer == 3:
        print(f"Computer {option[2]}")
    
def game2(your_score, computer_score):
    print("ok, lets start")
    time.sleep(1)
    print(3)
    time.sleep(1)
    print(2)
    time.sleep(1)
    print(1)
    time.sleep(1)
    while your_score != 2 or computer_score != 2:
        if your_score == 2 or computer_score == 2:
            break
        user = int(input("What do you shoot?\n1.rock\n2.paper\n3.scissors\n"))
        computer = random.choice([1, 2, 3])
        show(user, computer)
        
        if user == computer:
            print("it's a tie\n")

        elif is_win(user, computer):
            print("you won\n")
            your_score  = 1

        else:
            print("you lost\n")
            computer_score  = 1
    
    if your_score == 2:
        print("You won, gg")

    elif computer_score == 2:
        print("You lost, nt")
        
def game3(your_score, computer_score):
    print("ok, lets start")
    time.sleep(1)
    print(3)
    time.sleep(1)
    print(2)
    time.sleep(1)
    print(1)
    time.sleep(1)
    while your_score != 3 or computer_score != 3:
        if your_score == 3 or computer_score == 3:
            break
        user = int(input("What do you shoot?\n1.rock\n2.paper\n3.scissors\n"))
        computer = random.choice([1, 2, 3])
        show(user, computer)
        
        if user == computer:
            print("it's a tie\n")

        elif is_win(user, computer):
            print("you won\n")
            your_score  = 1

        else:
            print("you lost\n")
            computer_score  = 1
    
    if your_score == 3:
        print("You won, gg")

    elif computer_score == 3:
        print("You lost, nt")
  

def is_win(user, computer):
    if (user == 1 and computer == 3) or (user == 2 and computer == 1) or (user == 3 and computer ==2):
        return True

def start():
    s = ()
    while s == "yes" or "no":
        s = str(input("Are you ready?'yes' or 'no'\n")).lower()

        if s == "yes":
            game(your_score, computer_score)
            break

        elif s == "no":
            print("ok, I'll wait")
            time.sleep(1)
            print(3)
            time.sleep(1)
            print(2)
            time.sleep(1)
            print(1)
            print("You should be ready now")
            time.sleep(1)
            game(your_score, computer_score)
            break

        else:
            print("wrong insert, try again")

def start2():
    s = ()
    while s == "yes" or "no":
        s = str(input("Are you ready?'yes' or 'no'\n")).lower()

        if s == "yes":
            game2(your_score, computer_score)
            break

        elif s == "no":
            print("ok, I'll wait")
            time.sleep(1)
            print(3)
            time.sleep(1)
            print(2)
            time.sleep(1)
            print(1)
            print("You should be ready now")
            time.sleep(1)
            game2(your_score, computer_score)
            break

        else:
            print("wrong insert, try again")

def start3():
    s = ()
    while s == "yes" or "no":
        s = str(input("Are you ready?'yes' or 'no'\n")).lower()

        if s == "yes":
            game3(your_score, computer_score)
            break

        elif s == "no":
            print("ok, I'll wait")
            time.sleep(1)
            print(3)
            time.sleep(1)
            print(2)
            time.sleep(1)
            print(1)
            print("You should be ready now")
            time.sleep(1)
            game3(your_score, computer_score)
            break

        else:
            print("wrong insert, try again")

def gamemode():
    g_m = 1
    while g_m == 1 or g_m == 2 or g_m == 3:
        print("1.The best of 1(up to 1 points)\n")
        print("2.The best of 3(up to 2 points)\n")
        print("3.The best of 5(up to 3 points)\n")
        try:    
            g_m = int(input("Which one you want to play?\n"))
            if g_m == 1:
                start()
                break

            elif g_m == 2:
                start2()
                break

            elif g_m == 3:
                start3()
                break

            else:
                print("wrong insert\n")
        except ValueError:
            print()
            print("wrong value, try again\n")

#actual program

gamemode()

I tried messing with the loop, but it didn't work in the end, so I just put in another loop inside. The loops while in my thoughts should work until these variables don't have a certain value but I might be wrong about it. The program itself might be looking weird and long in a run but it was on purpose to train using a time.sleep. Thank you

CodePudding user response:

Generally you are not making functions that are flexible enough to change. You should think about how you can re-use components to reduce repetition. On that note, you are also not making enough functions and repeating a lot of logic.

For example, to count down from a number you could write:

def print_countdown(count):
    while count > 0:
        time.sleep(1)
        print(count)
        count -= 1

Now that can be used everywhere you do a countdown.

For getting user inputs, you repeat your while loop logic a lot. This can be isolated into it's own method:

def user_choice(prompt, choices):
    while True:
        choice = input(prompt)
        if choice not in choices:
            print("Invalid choice try again...")
        else:
            return choice

With example:

choice = user_choice("Are you ready?'yes' or 'no'\n", ["yes", "no"])

Next, if instead of using an index to your options, you actually just used the string values themselves, your methods for printing options and testing a win become much simpler:

def show(user, computer):
    print(f"You: {user}")
    print(f"Computer: {computer}")


def is_win(user, computer):
    return (user, computer) in (
        ("rock", "scissors"), 
        ("paper", "rock"), 
        ("scissors", "paper"),
    )

For the main game method, have the target score of the user passed in, and check that for the win condition. This will allow you to remove the gameN methods. And you can re-use the helper methods you made.

def game(target_score):
    your_score = 0
    computer_score = 0

    print("ok, lets start")
    print_countdown(3)

    while your_score != target_score and computer_score != target_score:
        user = user_choice("What do you shoot?\nrock\npaper\nscissors\n", option)
        computer = random.choice(option)

        show(user, computer)

        if user == computer:
            print("it's a tie\n")
        elif is_win(user, computer):
            print("you won\n")
            your_score  = 1
        else:
            print("you lost\n")
            computer_score  = 1

    if your_score == target_score:
        print("You won, gg")
    else:
        print("You lost, nt")

Similarly this can be done for the other methods!

def start(target_score):
    choice = user_choice("Are you ready?'yes' or 'no'\n", ["yes", "no"])

    if choice == "no":
        print("ok, I'll wait")
        print_countdown(3)
        print("You should be ready now")

    game(target_score)


def gamemode():
    choice = user_choice(
        "1.The best of 1(up to 1 points)\n"
        "2.The best of 3(up to 2 points)\n"
        "3.The best of 5(up to 3 points)\n",
        ["1", "2", "3"]
    )
    if choice == "1":
        start(1)
    elif choice == "2":
        start(2)
    else:
        start(3)

Finally make sure to test that the application is being called as a script vs loaded as a module. This will allow you to use the game methods in other projects without accidentally starting the game by simply importing the module

if __name__ == "__main__":
    gamemode()

CodePudding user response:

Here is how I would do a rock paper scissors game:

import random

options = ["rock", "paper", "scissors"]
your_score = 0
computer_score = 0
max_score = 3
playing = True

while playing:
    your_option = input(f"Options:\n - {options[0]}\n - {options[1]}\n - {options[2]}\nYour option: ")
    computer_option = random.choice(options)
    if your_option.lower() == 'rock':
        if computer_option == 'rock':
            print('Tie')
        elif computer_option == 'paper':
            print('Computer wins')
            computer_score  = 1
        elif computer_option == 'scissors':
            print('You win')
            your_score  = 1

    elif your_option.lower() == 'paper':
        if computer_option == 'rock':
            print('You win')
            your_score  = 1
        elif computer_option == 'paper':
            print('Tie')
        elif computer_option == 'scissors':
            print('Computer wins')
            computer_score  = 1

    elif your_option.lower() == 'scissors':
        if computer_option == 'rock':
            print('Computer wins')
            computer_score  = 1
        elif computer_option == 'paper':
            print('You win')
            your_score  = 1
        elif computer_option == 'scissors':
            print('Tie')

    else:
        print("Wrong input!")

    # Checking if score is max score
    if your_score >= max_score:
        print("You won the game")
        playing = False
    elif computer_score >= max_score:
        print("You lost the game")
        playing = False

If you want you can have a function called main() or game() which you will call at the very bottom of your code and that function should contain this while loop. IMPORTANT! Then you need to use global variable at the start so your_score and computer_score change values.

  • Related