-1

My Problem(s): The problem now is that whenever I enter a number of times to play, it just ignores it and plays forever. It is also not updating the score even though I have global variables and I am adding to them every time there is a win or loss.

My Program Also, I do not want to ask the player(s) for their names every time they play (only when using the "out of a certain number of points function of the game). Any suggestions/help would be greatly appreciated!

My code is below for reference:

from random import randint
import sys

print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
bestOutOf = int(input("Best out of: (Enter a number 1-10) "))

player1score = 0
player2score = 0
computerscore = 0

class PlayWithFriend:
    def __init__(self, player1, player2, name1, name2, player1score, player2score):

        self.player1 = player1
        self.player2 = player2
        self.name1 = name1
        self.name2 = name2
        self.player1score = player1score
        self.player2score = player2score

        if player1 == player2:
                print("Tie!")
        elif player1 == "Rock":
            if player2 == "Paper":
                print("You Win", name2,"!")
                print(player2, "covers", player1)
                player2score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
            else:
                print("You Win", name1,"!")
                print(player1, "smashes", player2)
                player1score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
        elif player1 == "Paper":
            if player2 == "Scissors":
                print("You Win", name2,"!")
                print(player2, "cut", player1)
                player2score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
            else:
                print("You Win", name1,"!")
                print(player1, "covers", player2)
                player1score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
        elif player1 == "Scissors":
            if player2 == "Rock":
                print("You Win", name2,"!")
                print(player2, "smashes", player1)
                player2score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
            else:
                print("You Win", name1,"!")
                print(player1, "cut", player2)
                player1score += 1
                print("The score is -->  %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
        else:
            print("That's not a valid play. Check your spelling!")

class PlayWithComputer:
    def __init__(self, player, name, player1score, computerscore):

        self.player = player
        self.player1score = player1score
        self.computerscore = computerscore
        self.name = name

        t = ["Rock", "Paper", "Scissors"]

        computer = t[randint(0,2)]

        if player == computer:
            print("Tie!")
            print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
        elif player == "Rock":
            if computer == "Paper":
                print("You lose!", computer, "covers", player)
                computerscore += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
            else:
                print("You win!", player, "smashes", computer)
                player1score += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
        elif player == "Paper":
            if computer == "Scissors":
                print("You lose!", computer, "cut", player)
                computerscore += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
            else:
                print("You win!", player, "covers", computer)
                player1score += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
        elif player == "Scissors":
            if computer == "Rock":
                print("You lose...", computer, "smashes", player)
                computerscore += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
            else:
                print("You win!", player, "cut", computer)
                player1score += 1
                print("The score is -->  %d: %s vs %d: computer" %(player1score, name, player2score))
        else:
            print("That's not a valid play. Check your spelling!")

if dotheywantotplay == "y":

    PlayWith = input("Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ")

    while  PlayWith in ('computer', 'friend', 'exit'):

        if PlayWith == "friend":

            player1 = input('Enter first players name: ')
            player2 = input('Enter second players name: ')
            while player1score + player2score < bestOutOf:

                personchoice1 = input("First player... Rock, Paper or Scissors?  ")
                personchoice2 = input("Second player... Rock, Paper or Scissors?  ")
                PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
        elif PlayWith == "computer":

            player = input('Enter first players name: ')
            while player1score + computerscore < bestOutOf:

                personchoice = input("Rock, Paper, Scissors?  ")
                PlayWithComputer(personchoice, player,  player1score, computerscore)
        elif PlayWith == "exit":
            sys.exit()

        else:
            print("That's not a valid play. Check your spelling!")
else:
    print("I am sad now :-(")
    sys.exit()
love2phish
  • 291
  • 2
  • 5
  • 15
  • 2
    `... or "friend" or "exit"` will always be True. That's not how conditions work. See [Compare to multiple values in an if statement](https://stackoverflow.com/q/29372848/2745495) or [How to test that variable is not equal to multiple things?](https://stackoverflow.com/q/12553609/2745495). – Gino Mempin Nov 26 '20 at 03:21
  • I know in Java you have to say, `somestring.equals(somestring);` for strings. I know there isn't really a `.equals()` in python though. If you could explain how to do it in Python that would be awesome. – love2phish Nov 26 '20 at 03:23
  • 2
    They linked to two different posts explaining how to do it in Python. Give those a look. – CrazyChucky Nov 26 '20 at 03:27
  • 1
    Check the links I commented above, they explain how to do it. Basically, a non-empty string is Truth-y in Python. So `if 1==2 or "friend"` will always be True. So you have to do `if this != that or this != something..` or use `in` as explained in [How to test that variable is not equal to multiple things?](https://stackoverflow.com/q/12553609/2745495) – Gino Mempin Nov 26 '20 at 03:30
  • Updated the code and question(about what while loops are messing up) above to use concepts found in the links provided. – love2phish Nov 26 '20 at 03:41
  • 2
    It's not usually a good idea to remove parts of your question after they're answered. It makes the answers make no sense. And if you discover new questions, it's usually best to post a new question (which, if helpful, can link to this one for context.) Remember, this isn't a forum discussion: the finished result should be a question and answer(s) that are meaningful together for others who may come across it later. – CrazyChucky Nov 26 '20 at 05:25
  • @CrazyChucky Sorry. Kinda to late now but will definitely keep that in mind in future questions. – love2phish Nov 26 '20 at 18:39

3 Answers3

2

I went over your code and cleaned it up. I made the formatting, variable names, and processes much more pythonic. You will find it is much easier to use python when you use these best practices, so I recommend you at least look over the code and see what I did. For me, I know this would've been helpful when I started learning python.

from random import choice


def get_result(choice1, choice2):
    return {
        ('paper', 'rock'): dict(win='player 1', action='covers'),
        ('rock', 'paper'): dict(win='player 2', action='covers'),
        ('rock', 'scissors'): dict(win='player 1', action='smashes'),
        ('scissors', 'rock'): dict(win='player 2', action='smashes'),
        ('scissors', 'paper'): dict(win='player 1', action='cuts'),
        ('paper', 'scissors'): dict(win='player 2', action='cuts'),
    }[(choice1, choice2)]  # index this dictionary


def main():
    print('Lets play a game!')
    if input('Do you want to play Rock-Paper-Scissors? (y or n) ') != 'y':
        quit()
    num_games = int(input('Best out of: (Enter a number 1-10) '))
    num_games = max(min(num_games, 10), 1)  # clamp num_games between 1-10
    while True:  # infinite loop, we can break out or quit when we need
        inp = input('Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ')
        if inp == 'exit':
            quit()
        play_with_computer = inp == 'computer'

        name1 = input('Enter first players name: ')
        name2 = 'computer' if play_with_computer else input('Enter second players name: ')

        score = {name1: 0, name2: 0}
        for game_number in range(num_games):
            choice1 = input(f'{name1}... rock, paper or scissors? ')
            choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ')
            if choice1 == choice2:
                print('Tie!')
                continue
            result = get_result(choice1, choice2)
            win_name = name1 if result['win'] == 'player 1' else name2
            lose_name = name2 if result['win'] == 'player 1' else name1
            score[win_name] += 1
            print(f'{win_name} {result["action"]} {lose_name}')
            print(f'Game {game_number+1}, the score is {score[name1]} {name1}, {score[name2]} {name2}')
        print(name1 if score[name1] > score[name2] else name2, 'wins!')


if __name__ == '__main__':  # this just means if the file is run
    main()

The main thing I did was get rid of your rock paper scissors logic, (which you repeated twice which is never best practice in programming), and replaced it with a get_result function which returns the winner and action of the moves. I also replaced your if statements that test if the game is against the computer, with a bool play_with_computer. This can be used when getting player 2 name and the second choice, which is all that is really different when playing with a computer. The last thing is your game loop while. Since you never really need to execute any code after this (only reason to exit is to quit), I find it to be cleaner to have an infinite loop while True, and just call quit() if the input is 'exit'.

Dharman
  • 30,962
  • 25
  • 85
  • 135
mazore
  • 984
  • 5
  • 11
  • Your awesome dude, thanks. I find the easiest way to learn the syntax and common jargon is by looking at fresh code so this is very helpful! – love2phish Nov 26 '20 at 04:50
  • 1
    @Cyclist can you share the error messages and the code from that line. Did you paste the code exactly? What IDE are you using? – mazore Nov 26 '20 at 05:10
  • After typing in `y 2 computer Batman rock` I get: Traceback (most recent call last): File "c:/User/USERNSAME/Pygame.py", line 33, in main() File "c:/User/USERNSAME/Pygame.py", line 19, in main choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ') NameError: name 'choice' is not defined. I am also using Visual Studio Code – love2phish Nov 26 '20 at 18:57
  • Is there a way to post pictures? Should I just post them in the question and then take them down after you get them? – love2phish Nov 26 '20 at 19:03
  • 1
    @Cyclist Sure. As long as you have the `from random import choice` at the top, I can't see why you'd be getting this error. Maybe you are doing `import random` instead of `from random import choice` – mazore Nov 26 '20 at 19:16
  • Got it. Now I am getting this error: Lets play a game! `Do you want to play Rock-Paper-Scissors? (y or n)` y `Best out of: (Enter a number 1-10)` 2 `Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit)` computer `Enter first players name:` Batman `Batman... rock, paper or scissors?` rock `Traceback (most recent call last): File "c:/Users/GonePhishing/Pygame.py", line 37, in main() File "c:/Users/GonePhishing/Pygame.py", line 27, in main result = get_result(choice1, choice2) NameError: name 'get_result' is not defined` – love2phish Nov 27 '20 at 01:20
  • The not-in-code-style-stuff after "Got it. Now I am getting this error:" above is stuff I entered as input. – love2phish Nov 27 '20 at 01:23
  • @Cyclist `NameError` means python cannot find the variable (functions are variables) you named. You probably didn't define the function `get_result` correctly (you need to define it above usage) – mazore Nov 27 '20 at 03:04
  • Thanks, I have no idea what happened. I copied and pasted all of your code, made sure of that. Must not have gotten all of it I guess. Thanks again for your help! The program works great and I hope my questions didn't make you think I was doubting your program. – love2phish Nov 27 '20 at 03:36
0

Okay so the mistake is: while PlayWith != "computer" or "friend" or "exit":

try this thing: while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":

And sorry if this does not work

0

which while loops and if statements are you having trouble with?

Upon first glance, the while statement below will never break the moment a player enters a value besides "computer", "friend" or "exit".

Instead, what you can do is put the process of the game within a function, that is continuously called back when the player enters a value besides the ones aforementioned.

while PlayWith != "computer" or "friend" or "exit":

        if PlayWith == "friend":

            player1 = input('Enter first players name: ')
            player2 = input('Enter second players name: ')

            personchoice1 = input("First player... Rock, Paper or Scissors?  ")
            personchoice2 = input("Second player... Rock, Paper or Scissors?  ")

            i = 0

            while i in range(0, bestOutOf):

                if i >= bestOutOf:
                    sys.exit()
                if bestOutOf >= 1 and bestOutOf <= 10:

                    PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
                    i += 1

                else:

                    print("Setting default game to: \"best out of three\"")
                    PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
                    i = bestOutOf - 3



        if PlayWith == "computer":

            i = 0

            while i in range(0, bestOutOf - 1):
                if i >= bestOutOf:
                    sys.exit()
                else:
                    player = input('Enter first players name: ')

                    if bestOutOf >= 1 and bestOutOf <= 10:

                        personchoice = input("Rock, Paper, Scissors?  ")
                        PlayWithComputer(personchoice, player,  player1score, computerscore)

                    else:

                        personchoice = input("Rock, Paper, Scissors?  ")
                        print("Setting default game to: \"best out of three\"")
                        PlayWithComputer(personchoice, player, player1score, computerscore)


        if PlayWith == "exit":
            sys.exit()

        elif PlayWith != "exit" or "computer" or "friend":
            print("That's not a valid play. Check your spelling!")
  • Like I commented, `while PlayWith != "computer" or "friend" or "exit"` will always be True. – Gino Mempin Nov 26 '20 at 03:32
  • @GinoMempin Sorry, yes. I changed it in the question. Maybe not to be correct, but to this: `while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":` as in the links you provided. – love2phish Nov 26 '20 at 03:43
  • @IsaacMarcusLam Is there any way you could explain or gin an example on how to put the game into a function? – love2phish Nov 26 '20 at 03:49