Pig Game in Python With Source Code

Pig Game in Python

If you’re looking for a lighthearted yet strategic game to enjoy with friends, the Pig Game might just be the perfect choice. Not only does it bring in elements of luck, but it also encourages players to think carefully about when to push their luck or when to play it safe. Now available as a Python project for everyone interested in coding and gaming, this game has gained popularity among casual players.


What is the Pig Game

Using a six-sided dice, the Pig Game is a straightforward yet entertaining game. All you need is a dice, some paper to keep score, and a strong sense of timing and chance. It may be played by two to ten people. Being the first player to get 100 points is the goal, but there’s a catch. Players must choose between holding and banking their points or continuing to roll the dice as they accrue points during their turn. They forfeit all of the points they earned during that turn if they roll a 1.

Download New Real Time Projects :-Click here


How Does the System Work

  1. Player Turn:
  • The player has the option to Hold or Roll.
  • A random number between 1 and 6 is produced when the dice are rolled.
  • The player’s turn ends and they forfeit all of the points they have accrued during that round if the dice land on 1.
  • The player has the option to keep and bank the points or roll again if the dice land on any number between 2 and 6.
  1. Hold Option:
  • The player’s points for that turn are added to their overall score if they decide to Hold.
  • After that, the following participant enters the game.
  1. Winning the Game:
  • The game is won by the first player to reach 100 points or more.
  • The game concludes with a winner being declared once this threshold is crossed.
See also  Expense Tracker in Python with Source Code

https://updategadh.com/category/php-project


Source Code

import random

# Define the Pig Game class
class PigGame:
    def __init__(self, players):
        self.players = players
        self.scores = [0] * players
        self.current_score = 0
        self.current_player = 0

    def roll_dice(self):
        # Simulate rolling a dice, returns a random number between 1 and 6
        return random.randint(1, 6)

    def hold(self):
        # Add current turn's score to the player's total score
        self.scores[self.current_player] += self.current_score
        print(f"Player {self.current_player + 1} holds. Total score: {self.scores[self.current_player]}")
        self.current_score = 0
        self.next_player()

    def next_player(self):
        # Switch to the next player
        self.current_player = (self.current_player + 1) % self.players
        print(f"Now, it's Player {self.current_player + 1}'s turn!")

    def play_turn(self):
        # Main gameplay loop for each turn
        while True:
            print(f"Player {self.current_player + 1}'s turn. Current score: {self.current_score}")
            choice = input("Roll or Hold? (r/h): ").lower()

            if choice == 'r':
                dice = self.roll_dice()
                print(f"Player {self.current_player + 1} rolled a {dice}.")

                if dice == 1:
                    print("Oops! Rolled a 1. You lose all points this turn!")
                    self.current_score = 0
                    self.next_player()
                    break
                else:
                    self.current_score += dice
                    print(f"Current turn score: {self.current_score}")
                    if self.scores[self.current_player] + self.current_score >= 100:
                        print(f"Player {self.current_player + 1} wins with {self.scores[self.current_player] + self.current_score} points!")
                        return True
            elif choice == 'h':
                self.hold()
                break
            else:
                print("Invalid input. Please type 'r' to roll or 'h' to hold.")

        return False

# Main function to start the game
def main():
    print("Welcome to the Pig Game!")
    players = int(input("Enter the number of players (2-10): "))

    # Create the game instance
    game = PigGame(players)

    # Continue the game until someone wins
    while True:
        if game.play_turn():
            print("Game Over. Thanks for playing!")
            break

if __name__ == "__main__":
    main()

How the Code Works:

  1. PigGame Class:
  • The PigGame class manages the gameplay, keeping track of each player’s score and determining the winner.
  • roll_dice mimics the action of rolling a die.
  • Hold enables the player to go on to the next player and add the points they have accrued to their overall score.
  • The turn is sent to the following player by using next_player.
  • Each player’s actions are managed by play_turn, which prompts them to hold or roll the dice.
  1. Gameplay Loop:
  • Until one player reaches 100 points or more, the game is over.
  • Following each dice roll, players can decide whether to “Roll” or “Hold” their points.
  • You lose all of your points for that turn if you roll a 1.
  1. Main Function:
  • This asks how many players (between two and ten) will join the game in the beginning.
  • Up until a winner is announced, the game goes on.
See also  Online Shopping System using PHP, MySQL with Free Source Code

How to Run the Game:

  1. Install Python if you haven’t already.
  2. Copy the code above into a Python file (e.g., pig_game.py).
  3. Run the file in your terminal:
   python pig_game.py
  • Pig Game in Python With Source Code

Post Comment