Created
February 6, 2025 12:44
-
-
Save Maxym403/0c1903a33666119a38ae197746906936 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tkinter as tk | |
import random | |
HALL = 0 | |
WALL = 1 | |
HERO = 4 | |
EXIT = 5 | |
height = 20 | |
width = 30 | |
cell_size = 40 | |
maze=[] | |
for y in range(height): | |
row = [] | |
for x in range(width): | |
row.append(random.randint(0, 1)) | |
maze.append(row) | |
for y in range(height): | |
for x in range(width): | |
if x == 0 or y == 0 or x == width - 1 or y == height - 1: | |
maze[y][x] = WALL | |
maze[height - 4][width - 1] = EXIT | |
hero_x, hero_y = 1, 1 | |
maze[hero_y][hero_x] = HERO | |
def draw_maze(): | |
for y in range(height): | |
for x in range(width): | |
if maze[y][x] == WALL: | |
draw_cell(x, y, "black") | |
elif maze[y][x] == EXIT: | |
draw_cell(x,y, "blue") | |
elif maze[y][x] == HALL: | |
draw_cell(x,y, "white") | |
elif maze[y][x] == HERO: | |
canvas.create_text((x + 0.5) * cell_size, (y + 0.5) * cell_size, | |
text="☺", font=("Arial", 16, "bold"), fill="black") | |
def draw_cell(x, y, color): | |
canvas.create_rectangle(x * cell_size, y * cell_size, | |
(x + 1) * cell_size, (y + 1) * cell_size, | |
fill=color, outline="black") | |
root = tk.Tk() | |
root.title("Maze Game") | |
canvas = tk.Canvas(root, width = width * cell_size, height = height * cell_size) | |
canvas.pack() | |
draw_maze() | |
def move_hero(move): | |
global hero_x, hero_y | |
new_x, new_y = new_position(hero_x, hero_y, move) | |
if maze[new_y][new_x] != WALL: | |
maze[hero_y][hero_x] = HALL | |
maze[new_y][new_x] = HERO | |
draw_maze() | |
elif maze[new_y][new_x] == EXIT: | |
print("Вітаємо! Ви знайшли вихід!") | |
root.quit() | |
def new_position(x, y, direction): | |
if direction == "up": | |
y -= 1 | |
elif direction == "down": | |
y += 1 | |
elif direction == "right": | |
x += 1 | |
elif direction == "left": | |
x -= 1 | |
return x, y | |
root.bind("<Up>", lambda event: move_hero("up")) | |
root.bind("<Down>", lambda event: move_hero("down")) | |
root.bind("<Left>", lambda event: move_hero("left")) | |
root.bind("<Right>", lambda event: move_hero("right")) | |
root.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment