连连看 python代码 tkinter模块
时间: 2024-06-16 07:02:35 浏览: 101
用Python Tkinter写的连连看小游戏
5星 · 资源好评率100%
连连看是一款经典的益智游戏,使用Python的Tkinter模块可以方便地创建一个基本的图形界面来实现。Tkinter是Python内置的一个图形用户界面(GUI)库,非常适合初学者入门。以下是一个简单的连连看游戏的Python代码示例,使用Tkinter和一些基本的事件处理:
```python
import tkinter as tk
import random
# 游戏矩阵大小
GRID_SIZE = 8
CELL_SIZE = 60
# 创建主窗口
root = tk.Tk()
root.title("连连看")
root.geometry(f"{GRID_SIZE * CELL_SIZE}x{GRID_SIZE * CELL_SIZE}")
# 初始化矩阵和鼠标位置
game_board = [[None] * GRID_SIZE for _ in range(GRID_SIZE)]
mouse_pos = None
def create_cells():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
cell = tk.Canvas(root, width=CELL_SIZE, height=CELL_SIZE)
cell.grid(row=i, column=j)
cell.bind("<Button-1>", lambda e: on_click(i, j))
if game_board[i][j] is not None:
cell.config(bg=game_board[i][j])
def on_click(row, col):
if game_board[row][col] == None:
return
if check_win(row, col):
game_over()
else:
swap_neighbors(row, col)
def check_win(row, col):
# 检查行、列以及左上到右下的对角线是否相邻
directions = [(0, 1), (1, 0), (0, -1), (1, 1), (-1, 1), (-1, -1)]
for direction in directions:
x, y = row, col
while 0 <= x < GRID_SIZE and 0 <= y < GRID_SIZE:
if game_board[x][y] != game_board[row][col]:
break
x, y = x + direction, y + direction
else:
return True
return False
def game_over():
# 游戏结束,这里可以添加胜利提示或重新开始逻辑
print("Game Over!")
root.quit()
create_cells()
root.mainloop()
```
阅读全文