Python Dice Game Tutorial
This post may contain affiliate links.
In this article, we will walk through how to create a dice game in Python from scratch! If you’re new to Python you can check our beginner tutorial!
How the Game Works
Before we start coding, let’s go over the rules of the game:
- Start with the numbers 1 – 9
- Each turn, the player rolls 2 dies and takes the sum of the numbers
- The player can then remove any of the numbers 1 – 9 that add up to the number that was rolled
- For example, if the player rolls a 7 they can either remove 7 or 4 and 3
- If the player successfully removes all of the numbers they win!
- If there are no moves that the player can make with the roll then they lose
Python Methods
Let’s first review a couple of methods that we will use in the game. Methods are functions that are built into Python that we can use on certain data structures. For example, there are string methods and list methods. The syntax for methods is a little bit different than using regular functions. Using a string method will look like this:
string.method(arg)
The data structure that the function is being applied to comes first (string), followed by a dot and then the name of the method. Finally, we end it with any arguments that the function takes in parentheses.
String Methods
One method that we will use is the string split method. The split method splits a string and returns a list with all of the split components. We can specify where we want to split with the argument. Let’s say we have a string s:
s = "a b c d" L = s.split(" ") print(L)
Our output will be:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
The argument to the method was a string that contained a space, and we can see the string s is split on the spaces.
List Methods
There are two list methods we will use: List.append(element) and List.remove(element)
The append method adds the element you give as the argument to the end of the list:
L = [1,2,3] L.append(4) print(L)
Output:
[1, 2, 3, 4]
The remove method removes the element you give as the argument:
L.remove(2) print(L)
Output:
[1, 3, 4]
Step 1: Importing Libraries
Python has many built-in functions. For example, len() is the built-in function that returns the length of the list. If you want to use other functions outside of what’s already in Python, you can import a library. A library contains functions that you can use once you import it!
For this game, we want to use the random library. The random library provides us with the random.randint() function. This function takes 2 numbers and randomly chooses a number in between them, and we can use this function to simulate rolling the dice. This is how we import the library:
import random
Step 2: Rolling the Dice
Before we jump into coding the main part of the game, there are a couple of things we want to do to make it a little easier. First we need to write a few helper functions. Each helper function will do one small part of the game for us. We will use them in the final larger playGame() function.
First, we want to write a rollDice() function, which will deal with rolling two dice and summing them. We will use the random.randint() function twice, to simulate rolling two die:
import random def rollDice(): roll1 = random.randint(1,6) roll2 = random.randint(1,6)
We also want to print to the player the results of the roll, as well as the sum:
def rollDice(): roll1 = random.randint(1,6) roll2 = random.randint(1,6) print("Rolled:", roll1, roll2) print("Sum:", roll1 + roll2)
Finally, we just need to return the sum to use later:
import random def rollDice(): roll1 = random.randint(1,6) roll2 = random.randint(1,6) print("Rolled:", roll1, roll2) print("Sum:", roll1 + roll2) return roll1 + roll2
Step 3: Keeping Track of Numbers
When the game begins, we start with the numbers 1-9. During each turn the player will remove some numbers, and we want to keep track of this. We will use a list to keep track of what numbers are still remaining:
numList = [1,2,3,4,5,6,7,8,9]
We want to write the function removeNums(numList, removeList). It will take two lists as arguments: numList is the current list of remaining numbers, and removeList is a list that will hold all the numbers we want to remove.
The removeList will be generated by player input, so we need to make sure that the player gave a valid set of numbers. This function will destructively modify numList, and it will also return True if the numbers are valid and False if not.
We can start by looping through the numbers we want to remove, removeList:
def removeNums(numList, removeList): for num in removeList:
Next, we want to check if the number is still in the remaining numbers, otherwise, we want to return False since that would be an invalid move.
def removeNums(numList, removeList): for num in removeList: if num in numList: numList.remove(num) else: return False
If all of the numbers are valid, we can return True:
def removeNums(numList, removeList): for num in removeList: if num in numList: numList.remove(num) else: return False return True
Step 4: Handling User Input
We will be using python’s built-in input() function to get input from the player. We will ask the player to enter what numbers they want removed separated by spaces. For example: “1 2”. The input function always returns a string, even if the user inputs numbers:
userInp = input("What's your favorite number? ") print(type(userInp))
Output:
What's your favorite number? 1234 <class 'str'>
Because of this, we need some way to turn this string into a list of integers. We will write the function formatInput(inputString) that takes in the input string and returns the numbers as integers in a list.
The first thing we want to do is use the split function to split the string on the spaces:
def formatInput(inputString): stringList = inputString.split(" ")
Now we have a list with all of the numbers. However, the numbers inside the list will still be strings. We want to loop through the list and use the built in int() function to convert all the strings to ints:
def formatInput(inputString): stringList = inputString.split(" ") intList = [] for s in stringList: intList.append(int(s)) return intList
Step 5: Putting it Together
Now we can start writing the main playGame() function. First thing we want to do is initialize the number list:
def playGame(): numList = [1,2,3,4,5,6,7,8,9]
We want the player to continue to be able to take turns until they either win or lose, we can acomplish this by using a while True loop. This type of loop allows us to keep looping until we manually break out of the loop using a break statement. Python will exit out of the loop as soon as it hits a break statement. This is what our while loop will look like:
def playGame(): numList = [1,2,3,4,5,6,7,8,9] while True:
Next, we want to print the current numbers to the player and then roll the dice for their turn. We will use the rollDice() helper function that we wrote previously:
def playGame(): numList = [1,2,3,4,5,6,7,8,9] while True: print(numList) # Roll the Dice roll = rollDice()
Next, we want to get input from the player to see which numbers they want to remove. Once we get the user input, we can use the formatInput(userInput) helper function that we wrote previously to format the input into an integer list.
def playGame(): numList = [1,2,3,4,5,6,7,8,9] while True: print(numList) # Roll the Dice roll = rollDice() # Get player input userInput = input("Numbers to remove (enter numbers separated by spaces) ") removeList = formatInput(userInput)
We now have a list of the numbers the player wants to remove: removeList.
At this point, there’s a chance the user may have given an invalid input, where the numbers that they gave don’t add up to the number that was rolled. If the player gives an invalid input, we will end the game by putting in a break statement. We can check for this using the built-in sum() function to check that the numbers in the removeList add up to the roll:
def playGame(): numList = [1,2,3,4,5,6,7,8,9] while True: print(numList) # Roll the Dice roll = rollDice() # Get player input userInput = input("Numbers to remove (enter numbers separated by spaces) ") removeList = formatInput(userInput) # Make sure input is valid if sum(removeList) != roll: print("Invalid Move. Game Over") break
Now we can try to remove the numbers that the player chose using the removeNums(numList, removeList) helper function that we previously wrote:
# Remove numbers validMove = removeNums(numList, removeList)
The function will return True or False depending on if the player chose numbers that were no longer in the list. We will save this value to a variable validMove. If the move is not valid, we will end the game:
# Remove numbers validMove = removeNums(numList, removeList) if not validMove: print("Invalid Move. Game Over") break
There is one last thing we need to check before we allow the player to start another turn: if there are no remaining numbers, the player has won and the game is over! We can do this by checking the length of numList:
def playGame(): numList = [1,2,3,4,5,6,7,8,9] while True: print(numList) # Roll the Dice roll = rollDice() # Get player input userInput = input("Numbers to remove (enter numbers separated by spaces) ") removeList = formatInput(userInput) # Make sure input is valid if sum(removeList) != roll: print("Invalid Move. Game Over") break # Remove numbers validMove = removeNums(numList, removeList) if not validMove: print("Invalid Move. Game Over") break elif len(numList) == 0: print("You Win!") break
And that’s it! Now we can put everything together and play the game:
import random def rollDice(): roll1 = random.randint(1,6) roll2 = random.randint(1,6) print("Rolled:", roll1, roll2) print("Sum:", roll1 + roll2) return roll1 + roll2 def removeNums(numList, removeList): for num in removeList: if num in numList: numList.remove(num) else: return False return True def formatInput(inputString): stringList = inputString.split(" ") intList = [] for s in stringList: intList.append(int(s)) return intList def playGame(): numList = [1,2,3,4,5,6,7,8,9] stillPlaying = True while True: print(numList) # Roll the Dice roll = rollDice() # Get player input userInput = input("Numbers to remove (enter numbers separated by spaces) ") removeList = formatInput(userInput) # Make sure input is valid if sum(removeList) != roll: print("Invalid Move. Game Over") break # Remove numbers validMove = removeNums(numList, removeList) if not validMove: print("Invalid Move. Game Over") break elif len(numList) == 0: print("You Win!") break playGame()
Here’s an example of the output of the game:
[1, 2, 3, 4, 5, 6, 7, 8, 9] Rolled: 2 3 Sum: 5 Numbers to remove (enter numbers separated by spaces) 5 [1, 2, 3, 4, 6, 7, 8, 9] Rolled: 5 5 Sum: 10 Numbers to remove (enter numbers separated by spaces) 6 4 [1, 2, 3, 7, 8, 9] Rolled: 6 5 Sum: 11 Numbers to remove (enter numbers separated by spaces) 8 3 [1, 2, 7, 9] Rolled: 6 6 Sum: 12 Numbers to remove (enter numbers separated by spaces) 9 2 1 [7] Rolled: 2 5 Sum: 7 Numbers to remove (enter numbers separated by spaces) 7 You Win!
Congrats on making your own dice game in Python!
Python Dice Game Digital Resource
Do you want all of the material covered in this tutorial in an easy to use in classroom lesson? Grab our Python Dice Game Tutorial!
- Comprehensive Python tutorial for teachers to introduce their students to Python.
- Includes a 5-page PDF worksheet with an answer guide and a 27-slide Google Slides presentation.
- Covers how to program a Dice Game in Python.
- PDF worksheet contains exercises that gradually develop students’ programming skills.
- Google Slides presentation is engaging and visually appealing, with interactive examples and illustrations.
- Suitable for both experienced and new programming instructors.
- Provides a solid foundation in Python programming for students to build on.
- An excellent resource to teach Python in a fun and effective way.
Want all our Python Tutorials?
- The Python Ultimate Bundle is an all-in-one package that includes all the Python tutorials you need to teach your students programming and game development.
- The bundle includes tutorials on Python Basics, Python Lists, creating a story in Python, Rock Paper Scissors game, Fortune Teller game, Create Your Own Adventure game, Blackjack game, and Dice game.
- Each tutorial is engaging, fun, and easy to follow with clear instructions and real-world examples.
- The bundle includes resources such as PDF worksheets, answer guides, and Google Slides presentations to help students learn at their own pace.
- This bundle is perfect for teachers who want to provide their students with a comprehensive introduction to Python programming and game development.
Want More Python?
If you are interested in learning more, check out our advanced Python tutorials here:
- Create a Rock, Paper, Scissors game with Python
- Create a fortune-telling game with Python
- Create a Blackjack game in Python
- Create a Choose Your Own Adventure Game in Python
Nazanin Azimi is a technical writer with several years of experience in the software industry. She is currently a senior at Carnegie Mellon studying computational physics and creative writing. She has been head teaching assistant for Principles of Computing, an introductory python and computer science course at CMU. She has held several technical internships including software engineering intern at Mathworks. Outside of technical writing, Nazanin also enjoys writing and studying poetry.