Dice Game in Python using While Loop

Learn how to create a simple Dice RollĀ game in python using while loop.

thecodingpie . . 7 min read . 1.3K Hits

Howdy folks welcome to this new tutorial. In this tutorial, you will learn how to create a simple Dice Rolling game in python using while loop. If you are an absolute beginner in python, then this would be the best start for you.

You can get the complete code here from my Github repo - Dice Game Python

Now, without further ado, let's get started...

The Game Plan

For the sake of simplicity, I am going to keep this game simple and straight forward.

In our Dice Rolling Game, we have to do the following:

  • Make a fake delay of 1 second (this is for making our game to feel a bit realistic. This is completely optional though)
  • After the delay, generate a random integer between 1 to 6.
  • Then print the random number to the screen
  • Then ask the user, if he/she wants to play again?
  • If the user types "yes" or "y", then repeat the above 4 steps.
  • If the user types anything besides "yes" or "y", then quit the game.

That's it! Sounds digestible right?

What you will learn?

By doing this simple project, you will learn the following:

  • while loop in python
  • how to make a delay using time.sleep()
  • how to generate random integers in python
  • how to print() output
  • how to take input()
  • == and or operators

Things you will need

  • The very first thing you will need is the python itself. I am going to use python3. You can read this post to learn how to setup python3 on any operating system - https://realpython.com/installing-python/
  • After setting up python3, you will need a modern code editor like visual studio code. Yes, of course, you can do this simple project inside the default python IDLE or things like that, but the benefit of using a modern code editor like visual studio code is that it comes pre-baked with all the things you will ever need during your programming journey. It has a pre-built terminal, Integrated Git, debugging tools, extensions, and much much more. And more than anything else, it is completely free and open-source. 

You can download visual studio code from here according to your Operating system - https://code.visualstudio.com/download.

With these things set up, now you are good to go.

Getting Started

  • Create a folder named Dice Game anywhere on your computer.
  • Now just open visual studio code.
  •  Then inside visual studio code, click on File > Open Folder and choose the folder you created Dice Game.
  • Now click on this icon to create a new file and name it as dice_game.py:

new file

  • Now you will have something similar to this:

file after creation

That's it now you are good to write the python code.

The Game

Let's import the needed modules first. Type the following code:

import random
import time
  • The first-line imports a module called random, which is used to generate random integers.
  • The second line imports a module called time. We can use this module to generate a delay in time

By the way, these modules already come pre-baked with python. So you don't have to install them separately.

Now we have the needed modules. So, let's define a global variable called roll_again.

Type the following code below the imports:

# Global variable
roll_again = "yes"
  • We can use this variable to keep track of the state of the game. By state, I mean whether we need to run the game or quit the game.
  • And see, I had already assigned it a string value "yes".

Now we need to do the following steps repeatedly:

  • Make a fake delay of 1 second.
  • After the delay, generate a random integer between 1 to 6.
  • Then print the random number to the screen
  • Then ask the user, if he/she wants to play again?
  • If the user types "yes" or "y", then repeat the above 4 steps.
  • If the user types anything besides "yes" or "y", then quit the game.

But how we are going to do these things repeatedly? Here's where the concept of loops comes into play.

There are so many types of loops. The one we are going to use here is what's called a while loop.

The syntax of the while loop is pretty straight forward and simple, you just give the keyword while and put the condition next to it like this:

while loop syntax

Now type this:

while roll_again == "yes" or roll_again == "y":
  print("Rolling the dice...")
  # make a delay of 1 second
  time.sleep(1)
  # create a random number b/w 1 to 6
  dice = random.randint(1, 6)
  # print the number
  print("Dice: ", dice)
  # ask the user to roll_again or not
  roll_again = input("Do you want to roll again? (yes/y)")
  # if the user entered "yes" or "y", the loop continues

# else, if the user entered anything besides "yes" or "y", the loop breaks and game ends
print("You ended the game!")

Now the explanation for the above code:

  • First, we are checking if the value of the roll_again variable is "yes" or "y" using the == operator. The double == operator is for checking both sides are equal or not and the single = operator is used for assigning the value to a variable. I hope you got that difference.
  •  The or is a keyword which literally means or. If you have more than one condition, then you join them using and or or
  • If any of the conditions are true, then:
    • we first print("Rolling the dice...")
    • After that make a delay in the time using the sleep() function which is available from the time module:

time.sleep(1) function in time module

  • After the delay, it's time to create a random number between 1 to 6. We generate the random number using the randint(lower_limit, upper_limit) function which is available from the random module:

randint() function

  • We store the random value in a variable called dice and then print() it to the screen.
  • Then ask the user "Do you want to roll again? (yes/y)" and take the value which the user enters as input() and store it in the same global variable roll_again. Which will overwrite the previous value in that variable with the new value the user had entered:

last line

  • The loop runs, again and again, if the user keeps typing "yes" or "y". But if the user types anything besides "yes" or "y", then the loop will break and print("You ended the game!") and quits the game:

very last line

That's it. Hooray, you have made the Dice Rolling Game in python! 

It's time to run the game! To run this python program in the terminal, do the following:

  • From within visual studio code, click on the Terminal > New Terminal:

new terminal opening steps

  • Now a terminal will pop up. In the terminal, enter the following code and hit the Enter key:
python3 dice_game.py

This is my output which I got:

final output

Complete Code

Here is the final code for the "dice_game.py" file. If you got any errors, then make sure the code you typed up to this point inside the "dice_game.py" is exactly like the following including the indentations for the while loop because indentation is everything in python:

import random
import time

# Global variable
roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
  print("Rolling the dice...")
  # make a delay of 1 second
  time.sleep(1)
  # create a random number b/w 1 to 6
  dice = random.randint(1, 6)
  # print the number
  print("Dice: ", dice)
  # ask the user to roll_again or not
  roll_again = input("Do you want to roll again? (yes/y)")
  # if the user entered "yes" or "y", the loop continues

# else, if the user entered anything besides "yes" or "y", the loop breaks and game ends
print("You ended the game!")

Wrapping Up

I hope you enjoyed this tutorial.

As an expansion to this Simple Dice game, why don't you try adding a second dice and make it a Multiple dice roll game?

If you had any doubts, then please comment them below. Thank you ;)

About Me

Hey folks, my name is Aravind, and I am the man behind this website. To know more about me, check out the About Me page. If you like and enjoy my content, then please consider supporting what I do through - Buy Me a coffee.

Comments(0) No Comments Yet :(
Leave Your Comments

Similar Posts

Let's Build a Web Scraper with Python & BeautifulSoup4

. 15 min read . 1.5K hits

A Quick Guide on How to Setup a Python Virtual Environment [Windows, Linux & Mac]

. 4 min read . 872 hits

How to build your own Python Voice Assistant | thecodingpie

. 10 min read . 7.3K hits

10 Best Python Courses Online | Learn Python Online | 2020

. 13 min read . 2.3K hits

Make your own text based adventure game in Python3

. 13 min read . 2.2K hits