Trouble with Classes/Functions

Question:

I am trying to make a game that involves two players who are taking turns guessing my random number. I want the computer to allow the players t continue guessing until the correct number is guessed. Once that happens, then I want the computer to print out the scores. Right now, when you run my code, it prints out the scores after each player takes one turn. I also want to know how to make the computer say which players turn it is. Any advice would be greatly appreciated as I am new to classes and objects. I wanted to make it clear that count is so that once there has been three rounds of the game, the game is over. Thank you in advance!

    import random

    class Players (object): 

      def __init__(self, name):
        self.name = name
        self.gamesWon = 0
        self.counter = 0

      def __str__(self):
            s = self.name + "'s score is " + str(self.gamesWon)
            return(s)

      def winFunction(self):
          self.gamesWon = self.gamesWon + 1

      def count (self):
        if self.counter < 4 :
          return True 
        else:
          return False

      def game(self):
        randomnumber = random.randint(1,10)
        print("Welcome to the Guessing Game! My number could be any number between 1-10!")
        rawguessednumber = input("What is your guess?")
        guessednumber = int(rawguessednumber)
        if randomnumber == guessednumber :
            print("You guessed it right!")
            self.gamesWon = self.gamesWon + 1
            self.counter = self.counter +1
        elif randomnumber < guessednumber :
            print("You guessed too high!")
        elif randomnumber > guessednumber :
            print("You guessed too low!")

    def main():
      player1 = Players("Ana")
      player2 = Players("Ryan")

      while player1.count() and player2.count():
        gamesWon = player1.game()
        gamesWon = player2.game()
        print (player1)
        print (player2)
      print ("The End!")

    main()
Asked By: Janet

||

Answers:

After the while loop in main(), make an if statement like so:

if player1.count:
    print("Player 1 wins!")
else:
    print("Player 2 wins!")

This simply checks who got to 3 first after knowing that somebody has ended the game.

Answered By: piip

I have changed the structure a little bit to make it more feasible to follow. First off, I added a Game class because it makes more sense to have it control a group of Player objects. I believe I have met your desired changes and game rules. I also added in some concepts for you to go over. This program will take in as many players as desired rather than you hard coding in each player for each iteration. Here it is:

import random


class Player:
    def __init__(self, name):
        """
        :param name: Name of the player
        """
        self.name = name
        self.games_won = 0
        self.random_number = None

    def win_function(self):
        self.games_won += 1

    def count(self):
        # In the original code, gamesWon = counter. Just use either one.
        # Also, games_won needs to be < 3 for three rounds.
        if self.games_won < 3:
            return True
        else:
            print(f'{self.name} has won!')
            return False

    def get_rand_number(self):
        self.random_number = random.randint(1, 10)

    def guess(self):
        guess = input(f"{self.name} Guess: ")
        guess = int(guess)

        if guess == self.random_number:
            print('You guessed it right!')
            self.get_rand_number()  # Get another random number for them to choose
            self.games_won += 1
        elif guess < self.random_number:
            print('You guessed too low!')
        else:
            print('You guessed too high!')

    def __str__(self):
        return f"{self.name}'s Score: {self.games_won}"


class Game:
    def __init__(self, *players):
        """
        :param players: Some arbitrary number of Player objects
        """
        self.players = players
        # list comprehension (assigns random number to each player)
        [player.get_rand_number() for player in self.players]

    def start(self):
        print('Welcome to the guessing game! Pick a number between 1 and 10. First to reach 3 guesses wins!n')

        while all([player.count() for player in self.players]):
            for player in self.players:
                player.guess()
                print(player)
                print()  # Adds space between players to make it more readable


player1 = Player('Ana')
player2 = Player('Ryan')
game = Game(player1, player2)
game.start()

One thing you should look into is the try and except blocks to handle the issue of a player inputting ‘dog’ instead of a number. Here is an example output:

Welcome to the guessing game! Pick a number between 1 and 10. First to reach 3 guesses wins!

Ana Guess: 5
You guessed too high!
Ana's Score: 0

Ryan Guess: 5
You guessed too high!
Ryan's Score: 0

Ana Guess: 4
You guessed too high!
Ana's Score: 0

Ryan Guess: 4
You guessed too high!
Ryan's Score: 0

Ana Guess: 3
You guessed too high!
Ana's Score: 0

Ryan Guess: 3
You guessed too high!
Ryan's Score: 0

Ana Guess: 2
You guessed too high!
Ana's Score: 0

Ryan Guess: 2
You guessed it right!
Ryan's Score: 1

Ana Guess: 1
You guessed it right!
Ana's Score: 1

Ryan Guess: 5
You guessed too low!
Ryan's Score: 1

Ana Guess: 5
You guessed too high!
Ana's Score: 1

Ryan Guess: 6
You guessed too low!
Ryan's Score: 1

Ana Guess: 4
You guessed too high!
Ana's Score: 1

Ryan Guess: 7
You guessed too low!
Ryan's Score: 1

Ana Guess: 3
You guessed too high!
Ana's Score: 1

Ryan Guess: 8
You guessed too low!
Ryan's Score: 1

Ana Guess: 2
You guessed it right!
Ana's Score: 2

Ryan Guess: 9
You guessed too low!
Ryan's Score: 1

Ana Guess: 5
You guessed too high!
Ana's Score: 2

Ryan Guess: 10
You guessed it right!
Ryan's Score: 2

Ana Guess: 1
You guessed too low!
Ana's Score: 2

Ryan Guess: 5
You guessed too low!
Ryan's Score: 2

Ana Guess: 2
You guessed too low!
Ana's Score: 2

Ryan Guess: 5
You guessed too low!
Ryan's Score: 2

Ana Guess: 3
You guessed it right!
Ana's Score: 3

Ryan Guess: 5
You guessed too low!
Ryan's Score: 2

Ana has won!
Answered By: Gabe Morris
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.