In this lesson you'll create a Rock-Paper-Scissors game using your Micro:bit and the Micro:bit will act as your opponent. You'll use the buttons to make your choice, generate a random choice for the computer using the random module, compare the outcomes with if-else statements, and display the results on the LED screen with messages like 'You win!'. We'll store the possible choices in a list to practise list handling.
By the end of this lesson, you'll have a fully interactive game. Open the Micro:bit Python editor at python.microbit.org and start a new project.
In this step, we'll import the necessary modules. We need the microbit module for hardware access and the random module to generate the computer's choice.
Start by adding the following complete code to your editor:
from microbit import *
import random
Next, we'll create a list to store the possible choices: rock, paper, and scissors. Lists are great for holding multiple related items, and we'll use this to select the computer's choice randomly.
Update your code to the following complete version:
from microbit import *
import random
choices = ["rock", "paper", "scissors"]
display.scroll("Ready")
Now, let's handle user input using the buttons. We'll decide: press button A for rock, button B for paper, and both buttons for scissors. We'll use a loop to wait for a button press.
The while True:
creates an infinite loop that keeps checking for button presses until one is detected. Inside the loop, we use
if-elif
statements to check which button(s) are pressed. When a condition is true, we assign the user's choice to a variable and use the break
statement. The
break
statement exits the loop immediately, stopping the continuous checking and allowing the program to continue with the next lines of code. The
sleep(100)
adds a short delay to prevent the loop from running too quickly and using too much processing power.
Update your code to this complete version:
from microbit import *
import random
choices = ["rock", "paper", "scissors"]
while True:
if button_a.is_pressed() and button_b.is_pressed():
user_choice = "scissors"
break
elif button_a.is_pressed():
user_choice = "rock"
break
elif button_b.is_pressed():
user_choice = "paper"
break
sleep(100)
display.scroll(user_choice)
if-else
for control.Let's make the Micro:bit choose randomly from the list. We'll use random.choice()
to pick one item.
Update your code to this complete version, adding the computer's choice after the user's:
from microbit import *
import random
choices = ["rock", "paper", "scissors"]
while True:
if button_a.is_pressed() and button_b.is_pressed():
user_choice = "scissors"
break
elif button_a.is_pressed():
user_choice = "rock"
break
elif button_b.is_pressed():
user_choice = "paper"
break
sleep(100)
computer_choice = random.choice(choices)
display.scroll("You: " + user_choice)
sleep(1000)
display.scroll("Comp: " + computer_choice)
display.scroll("You: " + user_choice)
. This can help if you want to just quickly test something.