python turtle 显示8*8的重力四子棋,用turtle.getcanvas显示鼠标所在的竖列
时间: 2024-05-03 08:21:26 浏览: 119
以下是一个示例代码,可以实现显示8*8的重力四子棋,并且用turtle.getcanvas显示鼠标所在的竖列:
```python
import turtle
# 定义棋盘大小和格子大小
board_size = 8
cell_size = 50
# 初始化turtle画布和画笔
canvas = turtle.getcanvas()
canvas.config(cursor="arrow")
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# 定义棋盘二维数组
board = [[0 for i in range(board_size)] for j in range(board_size)]
# 定义落子函数
def drop_piece(column, player):
for row in range(board_size-1, -1, -1):
if board[row][column] == 0:
board[row][column] = player
return True
return False
# 定义绘制棋盘函数
def draw_board():
pen.penup()
pen.goto(-board_size*cell_size/2, board_size*cell_size/2)
pen.pendown()
for i in range(board_size+1):
pen.forward(cell_size*board_size)
pen.right(90)
pen.forward(cell_size)
pen.left(90)
pen.forward(cell_size*board_size)
pen.left(90)
pen.forward(cell_size)
pen.right(90)
pen.penup()
# 定义绘制棋子函数
def draw_piece(row, col, player):
pen.penup()
pen.goto(col*cell_size-cell_size/2, -row*cell_size+cell_size/2)
pen.pendown()
pen.dot(cell_size*0.8, player)
# 定义显示鼠标所在竖列函数
def show_column(x, y):
column = int((x+board_size*cell_size/2)//cell_size)
if column >= 0 and column < board_size:
canvas.config(cursor="hand1")
pen.clear()
pen.penup()
pen.goto(column*cell_size-cell_size/2, board_size*cell_size/2)
pen.pendown()
pen.forward(cell_size*board_size)
canvas.coords(canvas.text, column*cell_size, board_size*cell_size+10)
canvas.itemconfigure(canvas.text, text=f'Column: {column}')
else:
canvas.config(cursor="arrow")
pen.clear()
canvas.itemconfigure(canvas.text, text='')
# 初始化棋盘和鼠标事件
draw_board()
canvas.bind('<Motion>', show_column)
canvas.text = canvas.create_text(board_size*cell_size/2, board_size*cell_size+10, text='', font=('Arial', 12))
# 开始游戏
player = 1
while True:
column = int(input(f'Player {player}, choose a column (0-{board_size-1}): '))
if drop_piece(column, player):
draw_piece(board_size-1, column, player)
player = 3 - player # 切换玩家
阅读全文