Mastermind
Crack a four-colour code with black and white pegs as hints. Teaches lists, a function with a return value and counting matches.
Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.
Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.
Flowchart
Python program
The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.
"""Guess the secret four-colour code in ten tries. Teaches lists and counting matches."""
from random import randint
# Tokbit screen functions, not in plain Python:
from tokbit import (
cls, at, color, background, border, beep, BLACK, WHITE, RED, CYAN, PURPLE,
GREEN, YELLOW, ORANGE, LIGHT_RED, LIGHT_GREEN,
)
def count(items: list[int], c: int) -> int:
"""How many times colour c is in the list."""
n: int = 0
for i in range(len(items)):
if items[i] == c:
n = n + 1
return n
background(BLACK)
border(BLACK)
cls()
colors: list[int] = [RED, GREEN, YELLOW, PURPLE, CYAN, ORANGE]
code: list[int] = []
for i in range(4):
code.append(randint(1, 6))
color(WHITE)
at(0, 0)
print("Colours:", end="")
for c in range(1, 7):
color(colors[c - 1])
at(10 + (c - 1) * 4, 0)
print(str(c) + "O", end="")
guess: str = ""
valid: bool = False
t: list[int] = []
attempt: int = 0
black: int = 0
white: int = 0
matches: int = 0
win: bool = False
while attempt < 10 and not win:
at(0, 22)
print(" " * 39, end="")
at(0, 22)
guess = input("Guess (4 digits 1 to 6):")
valid = len(guess) == 4
for i in range(len(guess)):
if guess[i] not in "123456":
valid = False
at(0, 20)
print(" " * 39, end="")
if valid:
attempt = attempt + 1
t = []
for i in range(4):
t.append(int(guess[i]))
black = 0
# Black peg: right colour in the right place.
for i in range(4):
if t[i] == code[i]:
black = black + 1
matches = 0
# Colour matches regardless of place; white pegs are matches minus black ones.
for c in range(1, 7):
matches = matches + min(count(code, c), count(t, c))
white = matches - black
for i in range(4):
color(colors[t[i] - 1])
at(2 + i * 2, 2 + attempt)
print("O", end="")
color(WHITE)
at(12, 2 + attempt)
print("black", black, "white", white, end="")
win = black == 4
beep(440 + black * 110, 60)
else:
color(LIGHT_RED)
at(0, 20)
print("Type four digits 1 to 6.", end="")
color(WHITE)
at(0, 20)
print(" " * 39, end="")
at(0, 22)
print(" " * 39, end="")
if win:
color(LIGHT_GREEN)
at(0, 20)
print("You cracked the code!", end="")
else:
color(LIGHT_RED)
at(0, 20)
print("Out of tries. Code:", end="")
for i in range(4):
color(colors[code[i] - 1])
at(24 + i * 2, 20)
print("O", end="")
color(WHITE)
at(0, 22)
Follow-up tasks
Tasks in which you change the example (with a model solution):