Roll the Dice with Python: Play the Classic Pig Game Right on Your Computer(with a built in Computer Player)!
Relive the thrill of the classic Pig dice game, now brought to life with Python! Test your luck, strategize, and play directly on your computer(or with the computer ;) ).

Hi everyone, today I would like to introduce to a neew game called Pig Game. It is a very classical game in which you have to roll a dice and have the total sum of your dice rolls to a specific amount, here in my case the goal is 40. But the twist is, if you roll a 1, then you score resets. So you have to be strategic about your dice roll and of course, have some GOOD LUCK!!
Basically, to sum the rules up(if you did not understand what the game is):
1. You will get to roll a dice once.
2. If the number is other than one, then the number will be added to your score.
3. If the number is one, then your score becomes zero and it's the next player's turn.
4. Whoever reaches 40 points first or more wins.
----------------------------------------------------------------------------------------
You can download the code from my GitHub Page here.
----------------------------------------------------------------------------------------
Suppose you do not have any of your friends to play with you. Of course, you cannot play this game alone, as it needs at least two players for a competition.
To resolve this problem I added a COMPUTER PLAYER which can play with you, even if you do not have anyone to play with you.
LET'S GET CODING!!!!
----------------------------------------------------------------------------------------
- Create a Python file and and save it in the appropriate folder.
- The most important step to start a python program, import the following modules:
import random
import time
3. Next, define all the lists, variables, and, if you want, rules:
# Emoji representations
dice_emojis = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"]
win_emoji = "🏆"
game_over_emoji = "❌"
print("Welcome to the PIG Game!!!")
num_players = int(input("How many human players are playing? ")) # Number of human players
# Ask for player names
player_names = []
for i in range(num_players):
name = input(f"Enter name for Player {i + 1}: ")
player_names.append(name)
# Add Computer player
player_names.append("Computer")
print("The rules of the game are:")
print("1. You will get to roll a dice once.")
print("2. If the number is other than one, then the number will be added to your score.")
print("3. If the number is one, then your score becomes zero and it's the next player's turn.")
print("4. Whoever reaches 40 points first or more wins.")
imput("Press Enter when you are ready.")
print("Let's play the game!!!!!\n")
# Initialize scores for each player
player_scores = [0] * (num_players + 1) # Additional slot for the computer player
# Target score
target_score = 40
4. Now, define main game loop:
# Main game loop
current_player = 0
while True:
print(f"\n{player_names[current_player]}'s turn:")
# Check if the current player is human or computer
if current_player < num_players:
is_human = True
else:
is_human = False
if is_human:
while True:
dice = random.randint(1, 6)
if dice == 1:
print("You rolled a 1!!! Your score becomes zero ", game_over_emoji)
player_scores[current_player] = 0
break
else:
print("You rolled:", dice_emojis[dice - 1])
player_scores[current_player] += dice
print("Your current score is", player_scores[current_player])
if player_scores[current_player] >= target_score:
print(f"Congratulations, {player_names[current_player]}! You reached {target_score} points or more and won the game!", win_emoji)
exit()
ask = input("Do you want to continue? (yes/no): ").lower()
if ask != "yes":
print(f"{player_names[current_player]} chose not to continue. Current score saved.")
break
else: # Computer player
rolls_left = 3
while rolls_left > 0:
dice = random.randint(1, 6)
if dice == 1:
print("Computer rolled a 1!!! Its score becomes zero ", game_over_emoji)
player_scores[current_player] = 0
break
else:
print("Computer rolled:", dice_emojis[dice - 1])
player_scores[current_player] += dice
print("Computer's current score is", player_scores[current_player])
rolls_left -= 1
current_player = (current_player + 1) % (num_players + 1)
5. In the end, print the score table in the end:
# Print scores table with emojis
print("\nScores Table:")
print("-" * 30)
for i in range(num_players + 1):
print(f"{player_names[i]}: {player_scores[i]}")
print("-" * 30)
----------------------------------------------------------------------------------------
The Explanation of the Code are as follows:
1. Emojis:
# Emoji representations
dice_emojis = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"]
win_emoji = "🏆"
game_over_emoji = "❌"
I added these emojis just for fun and make the game looks better. You can just copy-paste and if you are a Mac user then you can press Control + Command + Space to open up the character keyboard and use it to write the emojis.
2. Setting Up the Game:
print("Welcome to the PIG Game!!!")
num_players = int(input("How many human players are playing? ")) # Number of human players
- Here, we greet the players and ask how many human players will participate.
- The input is converted to an integer because it represents the number of players.
# Ask for player names
player_names = []
for i in range(num_players):
name = input(f"Enter name for Player {i + 1}: ")
player_names.append(name)
- We prompt the user to enter the names of the players.
- The names are stored in the 'player_names' list.
# Add Computer player
player_names.append("Computer")
- We add a computer player to the game automatically.
- This will allow the game to always have one Computer opponent.
print("The rules of the game are:")
print("1. You will get to roll a dice once.")
print("2. If the number is other than one, then the number will be added to your score.")
print("3. If the number is one, then your score becomes zero and it's the next player's turn.")
print("4. Whoever reaches 40 points first or more wins.")
imput("Press Enter when you are ready.")
print("Let's play the game!!!!!\n")
- We display the rules of the game and ask the player when they are ready.
- Whenever they are ready, Press Enter to begin the game.
3. Initializing Game Variables:
player_scores = [0] * (num_players + 1) # Additional slot for the computer player
- We initialize the scores for each player, including the computer.
- All scores start at zero.
- The list size is 'num_players + 1' to accommodate both human and computer players.
# Target score
target_score = 40
- We set the target score to 40.
- The first player to reach this score wins the game.
- You can change this number to whatever you want as the final score needed.
4. Main Game Loop:
# Main game loop
current_player = 0
while True:
print(f"\n{player_names[current_player]}'s turn:")
- The game enters an infinite loop where each player gets a turn.
- We keep track of the current player with 'current_player', which starts at 0 (the first player).
5. Human Player Turn:
# Check if the current player is human or computer
if current_player < num_players:
is_human = True
else:
is_human = False
- Here, we determine if the current player is human or computer.
- If 'current_player' is less than 'num_players', it's a human player's turn. Otherwise, it's the computer's turn.
if is_human:
while True:
dice = random.randint(1, 6)
if dice == 1:
print("You rolled a 1!!! Your score becomes zero ", game_over_emoji)
player_scores[current_player] = 0
break
else:
print("You rolled:", dice_emojis[dice - 1])
player_scores[current_player] += dice
print("Your current score is", player_scores[current_player])
- If it's a human player's turn, the code enters another loop where the player rolls the dice.
- If they roll a 1, their score is reset to zero, and the loop breaks to move to the next player.
- If they roll any other number, their score is updated, and they are prompted if they want to continue rolling.
if player_scores[current_player] >= target_score:
print(f"Congratulations, {player_names[current_player]}! You reached {target_score} points or more and won the game!", win_emoji)
exit()
- If the player's score reaches or exceeds the target score, they win the game, and the program exits.
ask = input("Do you want to continue? (yes/no): ").lower()
if ask != "yes":
print(f"{player_names[current_player]} chose not to continue. Current score saved.")
break
- If the player decides not to continue, their current score is saved, and the game proceeds to the next player.
6. Computer Player Turn:
else: # Computer player
rolls_left = 3
while rolls_left > 0:
dice = random.randint(1, 6)
if dice == 1:
print("Computer rolled a 1!!! Its score becomes zero ", game_over_emoji)
player_scores[current_player] = 0
break
else:
print("Computer rolled:", dice_emojis[dice - 1])
player_scores[current_player] += dice
print("Computer's current score is", player_scores[current_player])
rolls_left -= 1
- For the computer player, the AI will roll the dice three times.
- If the computer rolls a 1, its score is reset to zero, and its turn ends. Otherwise, the computer adds the dice roll to its score.
- If you want that the computer to play more rolls, you can just change the 'rolls_left' to whatever number you want.
7. End of Turn and Scoreboard:
current_player = (current_player + 1) % (num_players + 1)
- We move to the next player using the modulo operator (%).
- This ensures that after the last player, the game goes back to the first player.
# Print scores table with emojis
print("\nScores Table:")
print("-" * 30)
for i in range(num_players + 1):
print(f"{player_names[i]}: {player_scores[i]}")
print("-" * 30)
After each round, the scores of all players (human and computer) are displayed on the scoreboard with emojis.
----------------------------------------------------------------------------------------
With just a few lines of Python code, you've learned how to create a fun and interactive Pig Game that combines strategy and luck. Whether you're a beginner or an experienced Python developer, this project highlights how Python can be used to create engaging games with simple mechanics. If you have any questions about the code or need further clarification, feel free to leave a comment below. If you enjoyed this project and want to explore more Python game development ideas, be sure to follow for future tutorials and code snippets. Happy coding and good luck with your dice rolls!
If you are still not following my GitHub Page, you can visit it here.

About the Creator
Enjoyed the story? Support the Creator.
Subscribe for free to receive all their stories in your feed.
Comments
There are no comments for this story
Be the first to respond and start the conversation.