第 1 步:制作
它是什么?
Play a maths game with your BBC micro:bit! Program it to choose a random number from 1 to 100. You can decide if the number is odd or even, and then use your micro:bit to test if you are right.
这两个视频介绍了你将制作什么以及如何编程:
学习目标
You’ll learn how to turn a simple mathematical algorithm into code, how to use selection in computer programs, and how to divide a number and use its remainder.
If you want the learning to focus on maths skills rather than coding, then the ready-made code is available to download right away. Click on 'Open in MakeCode' or download the hex file below.
工作原理
- This program is based on an algorithm for working out if a number is odd or even. The algorithm says: divide the number by two and if the remainder is 0, the number is even. Otherwise the number is odd.
- When you press button A, the program picks a random number between 1 and 100 and shows it on the micro:bit’s LED display. (The program picks a random number rather than the same number each time to make the game fun to play more than once.)
- When you press button B, the program divides the number by 2 and works out its remainder.
- The program then uses an ‘if… else’ statement. If the remainder is 0, the word ‘even’ appears on the micro:bit’s LED display. Else, it shows the word ‘odd’.
- When different things can happen based on different conditions in a computer program like this, it is known as selection. You'll find key terms like selection explained in our vocabulary posters and glossary.
所需材料
- micro:bit或者是MakeCode模拟器
- MakeCode 或者 Python 编辑器
- 电池盒(选配)
第 2 步:编程
1from microbit import *
2import random
3
4# An error could appear if you press button B without pressing button A first.
5# If the variable ‘number’ has not been assigned.
6# To work around this, the value of 101 is assigned to the variable 'number'
7# at the start of the program. When you press button B the program tests
8# first to see if the value of ‘number’ is 101 - if it is, it shows a helpful message.
9
10number = 101
11
12while True:
13 if button_a.was_pressed():
14 number = random.randint(1, 100)
15 display.scroll(number)
16 if button_b.was_pressed():
17 if number == 101:
18 display.scroll('no number chosen yet')
19 elif number%2 == 0:
20 display.scroll('even')
21 else:
22 display.scroll('odd')
第3步:完善
- Find a way to show the random number chosen more than once.
- If you press button B before pressing button A, no random number will have been chosen and the LED display will show the word 'even'. Can you adapt the code so this doesn't happen? Look at the Python version of the program for an idea of how.
- Adapt the program to explore other factors of numbers, for example, if 3 is a factor of 100.
This content is published under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) licence.