Игра Раскраска написана на Питоне с использованием графической библиотеки Tkinter. Правила игры просты, необходимо закрасить всё поле в один цвет начиная с левого верхнего угла.
Закрашиваются только области, совпадающие по цвету и смежные с левым верхним углом. Игрок сообщает в программу цвет, в который хочет красить кликнув мышью по игровому полю. Программа написана на Python с использованием графической библиотеки Tkinter. Устанавливать программу нет необходимости. На компьютере, с любой операционной системой, где предустановлен Python 3 программа запускается из командной строки по имени файла. Так же запустить программу можно из среды Python или из любой IDE Python3, например IDLE.
#!/usr/bin/python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width:$
# Painter
# This is my version of the game, known as Filler.
#
# Created on July 5, 2021.
# Author of this program code : Diorditsa A.
# I thank Sergey Polozkov for checking the code for hidden errors?
#
# painter.py is distributed in the hope that it will be useful, but
# WITHOUT WARRANTY OF ANY KIND; not even an implied warranty
# MARKETABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See. See the GNU General Public License for more information.
# You can get a copy of the GNU General Public License
# by link http://www.gnu.org/licenses/
from tkinter import *
from random import choice
SIDE = 17; SIZE = 47 # элементов, пикселей
COLORSCHEMES = ('#f00','#0f0','#00f','#ff0','#d7f','#988') # RGB
PLAYGROUND = [] # Цветное поле int
nextColor = oldColor = 0 # Новый цвет и цвет в левом верхнем углу
def play(self):
global nextColor, oldColor
n = self.x//SIZE + self.y//SIZE*SIDE
nextColor = PLAYGROUND[n]
oldColor = PLAYGROUND[0]
if nextColor != oldColor: # не запускать бесконечную рекурсию (масло маслянное)
zone(0, 0)
elif n == 0:
newGame()
doDraw()
def zone(x, y): # Author of this algorithm : Diorditsa A.
if x in range(0, SIDE) and y in range(0, SIDE):
global nextColor, oldColor
if PLAYGROUND[x+y*SIDE] == oldColor:
PLAYGROUND[x+y*SIDE] = nextColor
zone(x+1, y)
zone(x, y+1)
zone(x-1, y)
zone(x, y-1)
def doDraw():
cnv.delete('rctng')
for j in range(SIDE):
for i in range(SIDE):
cnv.create_rectangle(i*SIZE, j*SIZE, (i+1)*SIZE, (j+1)*SIZE,
fill=COLORSCHEMES[PLAYGROUND[(i)+(j*SIDE)]],
width=0, tag='rctng')
cnv.tkraise('txtStart')
def newGame():
PLAYGROUND.clear()
for i in range(SIDE*SIDE):
PLAYGROUND.append(choice(range(6)))
tk = Tk()
tk.title('Раскраска')
cnv = Canvas(width=SIDE*SIZE, height=SIDE*SIZE, bg='white')
cnv.pack(expand=YES, fill=BOTH)
cnv.bind('<Button-1>', play)
cnv.create_text(SIZE//2, SIZE//2, text='Start', anchor=CENTER, tag='txtStart')
newGame()
doDraw()
mainloop()
Листинг 1. Программа на Python, файл painter.py
Обратите внимание, функция zone() использует рекурсию, благодаря чему удалось в таком коротком коде уместить такой функционал. Учитесь.
Рис. 1. Игра "Раскраска".
#!/usr/bin/python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width:$
# Painter
# This is my version of the game, known as Filler.
#
# Created on March 6, 2025.
# Author of this program code : Diorditsa A.
#
# painter.py is distributed in the hope that it will be useful, but
# WITHOUT WARRANTY OF ANY KIND; not even an implied warranty
# MARKETABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See. See the GNU General Public License for more information.
# You can get a copy of the GNU General Public License
# by link http://www.gnu.org/licenses/
from tkinter import *
from random import choice
side = 17; size = 47 # Клеток, пикселей
colorschemes = ('#f00','#0f0','#00f','#ff0','#d7f','#988') # RGB
playground = [] # Цветное поле содержит номера цветов int
def play(event):
n = event.x//size + event.y//size * side
if n == 0:
newgame()
elif playground[n] != playground[0]: # Не запускать бесконечную рекурсию
zone(0, playground[n], playground[0])
paint()
def zone(n, nextcolor, oldcolor): # Author of this algorithm : Diorditsa A.
if playground[n] == oldcolor:
playground[n] = nextcolor
[zone(i, nextcolor, oldcolor) for i in [n+side, n-side] + [j for j in [n-1, n+1] if j//side==n//side] if i in range(0, side*side)]
def newgame():
playground.clear()
for i in range(side*size):
playground.append(choice(range(6)))
paint()
def paint():
Cnv.delete('rctng')
for i in range(side):
for j in range(side):
Cnv.create_rectangle(i*size, j*size, (i+1)*size, (j+1)*size, fill=colorschemes[playground[j*side+i]], tag='rctng')
Cnv.tkraise('txtStart')
Cnv = Canvas(width=side*size, height=side*size)
Cnv.pack(expand=YES, fill=BOTH)
Cnv.bind('<Button-1>', play)
Cnv.create_text(size//2, size//2, text='Start', anchor=CENTER, tag='txtStart')
newgame()
mainloop()
Листинг 2. Функционально, то же самое, что и в листинге 1.