python 用鼠标追踪位置 重力四子棋 turtle 代码
时间: 2024-05-14 14:14:12 浏览: 75
以下是使用turtle模块实现的重力四子棋游戏代码,包括用鼠标追踪位置:
```python
import turtle
# 棋盘大小
BOARD_SIZE = 7
# 棋子大小
PIECE_SIZE = 40
# 棋盘左上角坐标
BOARD_LEFT = -200
BOARD_TOP = 200
# 棋子颜色
PLAYER1_COLOR = 'red'
PLAYER2_COLOR = 'yellow'
# 初始化棋盘
board = [[0] * BOARD_SIZE for i in range(BOARD_SIZE)]
# 初始化玩家
current_player = 1
# 初始化游戏结束标志
game_over = False
# 初始化画布和画笔
screen = turtle.Screen()
screen.title('Gravity Four')
screen.setup(width=600, height=600)
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# 绘制棋盘
def draw_board():
pen.penup()
pen.goto(BOARD_LEFT, BOARD_TOP)
pen.pendown()
for i in range(BOARD_SIZE + 1):
pen.goto(BOARD_LEFT + i * PIECE_SIZE, BOARD_TOP)
pen.goto(BOARD_LEFT + i * PIECE_SIZE, BOARD_TOP - BOARD_SIZE * PIECE_SIZE)
pen.goto(BOARD_LEFT, BOARD_TOP)
for i in range(BOARD_SIZE + 1):
pen.goto(BOARD_LEFT, BOARD_TOP - i * PIECE_SIZE)
pen.goto(BOARD_LEFT + BOARD_SIZE * PIECE_SIZE, BOARD_TOP - i * PIECE_SIZE)
# 绘制棋子
def draw_piece(row, col, player):
x = BOARD_LEFT + col * PIECE_SIZE + PIECE_SIZE / 2
y = BOARD_TOP - row * PIECE_SIZE - PIECE_SIZE / 2
pen.penup()
pen.goto(x, y)
if player == 1:
pen.color(PLAYER1_COLOR)
else:
pen.color(PLAYER2_COLOR)
pen.begin_fill()
pen.circle(PIECE_SIZE / 2)
pen.end_fill()
# 检查是否有四个相连的棋子
def check_win(row, col):
directions = [(1, 0), (0, 1), (1, 1), (-1, 1)]
for d in directions:
count = 1
r, c = row, col
while True:
r += d[0]
c += d[1]
if r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] != current_player:
break
count += 1
r, c = row, col
while True:
r -= d[0]
c -= d[1]
if r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] != current_player:
break
count += 1
if count >= 4:
return True
return False
# 点击事件处理函数
def click_handler(x, y):
global current_player
global game_over
if game_over:
return
col = int((x - BOARD_LEFT) / PIECE_SIZE)
if col < 0 or col >= BOARD_SIZE:
return
row = -1
for i in range(BOARD_SIZE):
if board[i][col] == 0:
row = i
break
if row == -1:
return
draw_piece(row, col, current_player)
board[row][col] = current_player
if check_win(row, col):
pen.penup()
pen.goto(BOARD_LEFT + BOARD_SIZE * PIECE_SIZE / 2, BOARD_TOP + PIECE_SIZE)
pen.write('Player {} wins!'.format(current_player), align='center', font=('Arial', 24, 'bold'))
game_over = True
return
current_player = 3 - current_player
# 鼠标移动事件处理函数
def move_handler(x, y):
if game_over:
return
col = int((x - BOARD_LEFT) / PIECE_SIZE)
if col < 0 or col >= BOARD_SIZE:
return
pen.clear()
draw_board()
for i in range(BOARD_SIZE):
if board[i][col] == 0:
draw_piece(i, col, current_player)
break
# 注册鼠标点击事件
screen.onclick(click_handler)
# 注册鼠标移动事件
screen.onmousemove(move_handler)
# 初始化游戏
draw_board()
# 运行游戏
turtle.mainloop()
```
使用方法:
将代码复制到Python编辑器中,运行代码并在弹出的窗口中玩游戏。鼠标移动到棋盘上方时,会显示当前玩家的棋子。点击棋盘时,会下一个棋子。当有一方获胜时,会显示获胜信息并结束游戏。
阅读全文