当前位置:首页 / 文章测试 / xzh想玩的小游戏

xzh想玩的小游戏

开始打字练习

import tkinter as tk

import random

# 窗口设置

root = tk.Tk()

root.title("迷宫闯关游戏")

CELL = 30 # 格子大小

ROW = 15

COL = 15

cv = tk.Canvas(root, width=COL*CELL, height=ROW*CELL, bg='white')

cv.pack()

# 迷宫数组 1墙 0通路

maze = []

start_x, start_y = 1, 1

end_x, end_y = COL-2, ROW-2

px, py = start_x, start_y

# 生成随机迷宫

def create_maze():

global maze

maze = [[1]*ROW for _ in range(COL)]

stack = [(start_x, start_y)]

maze[start_x][start_y] = 0

dirs = [(-2,0),(2,0),(0,-2),(0,2)]

while stack:

x,y = stack[-1]

random.shuffle(dirs)

find = False

for dx,dy in dirs:

nx = x+dx

ny = y+dy

if 0<nx<COL-1 and 0<ny<ROW-1 and maze[nx][ny]==1:

maze[(x+nx)//2][(y+ny)//2] = 0

maze[nx][ny] = 0

stack.append((nx,ny))

find = True

break

if not find:

stack.pop()

# 绘制迷宫

def draw_maze():

cv.delete("all")

for x in range(COL):

for y in range(ROW):

if maze[x][y] == 1:

cv.fill_rect = cv.create_rectangle(

x*CELL, y*CELL, (x+1)*CELL, (y+1)*CELL, fill="#333333"

)

# 终点绿色

cv.create_rectangle(end_x*CELL+5, end_y*CELL+5,

(end_x+1)*CELL-5, (end_y+1)*CELL-5, fill="#2ecc71")

# 玩家蓝色

cv.create_oval(px*CELL+5, py*CELL+5,

(px+1)*CELL-5, (py+1)*CELL-5, fill="#3498db", tag="player")

# 移动玩家

def move(event):

global px, py

key = event.keysym

nx, ny = px, py

if key == "Up":

ny -= 1

elif key == "Down":

ny += 1

elif key == "Left":

nx -= 1

elif key == "Right":

nx += 1

# 撞墙判断

if 0<=nx<COL and 0<=ny<ROW and maze[nx][ny]==0:

px, py = nx, ny

draw_maze()

# 到达终点

if px == end_x and py == end_y:

cv.create_text(COL*CELL//2, ROW*CELL//2, text="恭喜通关!", font=("黑体",20), fill="red")

# 初始化游戏

create_maze()

draw_maze()

root.bind("<KeyPress>", move)

root.mainloop()

声明:以上文章均为用户自行发布,仅供打字交流使用,不代表本站观点,本站不承担任何法律责任,特此声明!如果有侵犯到您的权利,请及时联系我们删除。

本文打字速度TOP10

  • 暂无打字数据!