/
floodit.py
96 lines (79 loc) · 2.86 KB
/
floodit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# ------------------------------
# Imports
# ------------------------------
from guizero import App, Waffle, Text, PushButton, info
import random
# ------------------------------
# Variables
# ------------------------------
colours = ["red", "blue", "green", "yellow", "magenta", "purple"]
board_size = 14
moves_limit = 25
moves_taken = 0
moves_countdown = moves_limit
# ------------------------------
# Functions
# ------------------------------
# Recursively floods adjacent squares
def flood(x, y, target, replacement):
# Algorithm from https://en.wikipedia.org/wiki/Flood_fill
if target == replacement:
return False
if board.get_pixel(x, y) != target:
return False
board.set_pixel(x, y, replacement)
if y+1 <= board_size-1: # South
flood(x, y+1, target, replacement)
if y-1 >= 0: # North
flood(x, y-1, target, replacement)
if x+1 <= board_size-1: # East
flood(x+1, y, target, replacement)
if x-1 >= 0: # West
flood(x-1, y, target, replacement)
# Check whether all squares are the same
def all_squares_are_the_same():
squares = board.get_all()
if all(colour == squares[0] for colour in squares):
return True
else:
return False
def win_check():
global moves_taken
moves_taken += 1
moves_countdown = str(moves_limit - moves_taken)
win_text.value = "Moves: " + str(moves_countdown)
if moves_taken < moves_limit:
if all_squares_are_the_same():
win_text.value = "You win with " + str(moves_limit - moves_taken) + " moves left!\nClick on any color to start a new game."
else:
if all_squares_are_the_same():
win_text.value = "You win with " + str(moves_limit - moves_taken) + " moves left!\nClick on any color to start a new game."
else:
win_text.value = "You lost :(\nClick on any color to start a new game."
if moves_taken > moves_limit:
moves_taken = 0
fill_board()
def fill_board():
moves_countdown = str(moves_limit - moves_taken)
win_text.value = "Moves: " + str(moves_countdown)
for x in range(board_size):
for y in range(board_size):
board.set_pixel(x, y, random.choice(colours))
def init_palette():
for colour in colours:
palette.set_pixel(colours.index(colour), 0, colour)
def start_flood(x, y):
flood_colour = palette.get_pixel(x,y)
target = board.get_pixel(0,0)
flood(0, 0, target, flood_colour)
win_check()
# ------------------------------
# App
# ------------------------------
app = App("Flood it")
board = Waffle(app, width=board_size, height=board_size, pad=0)
palette = Waffle(app, width=6, height=1, dotty=True, command=start_flood)
win_text = Text(app)
fill_board()
init_palette()
app.display()