Python Simple Dice Game
Here’s a simple program in Python that demonstrates some important fundamental concepts in computer programming. The program simulates two players taking it in turns to roll a 6-sided dice, and keeps track of the scores. It makes use of the three basic control structures of sequence, selection and iteration.
This involves thinking about the order in which instructions need to be executed to produce the desired result.
This involves choosing (selecting) different paths through a program based on conditions specified by the programmer.
One of the most powerful aspects of computers is their ability to perform repetition. Iteration is a kind of repetition which often involves loops such as
for loops and
As well as these 3 basic control structures, This simple program covers some other important fundamental programming skills.
- Creating variables, using descriptive names
- Working with strings and integers
- Outputting information to the screen
- Updating the value of a variable
- Creating random values using Python’s
- Python comparison operators
random module is used to simulate rolling a 6-sided dice using
random.randint(1, 6). According to the docs, this functions
Gets a random integer in the range [a, b] including both end points.
Before looking at the listing below, you might want to try and write the program for yourself, if you have sufficient knowledge for the task to be within reach of your ability. Otherwise you should type the code into a Python editor such as IDLE, rather than copy/pasting, run the program, and then see if you can work out how the program produces the result that it does.
Python Simple Dice Game Code Listing
# Needed to create random numbers to simulate dice roll import random # Initialise player scores to 0 player1_score = 0 player2_score = 0 # Repeat everything in this block 10 times for i in range(10): # Generate random numbers between 1 and 6 for each player. player1_value = random.randint(1, 6) player2_value = random.randint(1, 6) # Display the values print("Player 1 rolled: ", player1_value) print("Player 2 rolled: ", player2_value) # Selection: based on comparison of the values, take the appropriate path through the code. if player1_value > player2_value: print("player 1 wins.") player1_score = player1_score + 1 # This is how we increment a variable elif player2_value > player1_value: print("player 2 wins") player2_score = player2_score + 1 else: print("It's a draw") input("Press enter to continue.") # Wait for user input to proceed. print("### Game Over ###") print("Player 1 score:", player1_score) print("Player 2 score:", player2_score)
This lesson has demonstrated several important programming concepts using the Python programming language. I hope it was helpful.