python重力四子棋用turtle 8*8的格子
时间: 2023-11-22 09:53:40 浏览: 85
以下是一个简单的重力四子棋游戏,使用 Python 的 turtle 模块实现,棋盘大小为 8x8:
```python
import turtle
# 定义棋盘大小和格子大小
BOARD_SIZE = 8
CELL_SIZE = 50
# 初始化 turtle
turtle.setup(BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE)
turtle.bgcolor("white")
turtle.tracer(0, 0)
# 画棋盘
def draw_board():
turtle.penup()
turtle.goto(-BOARD_SIZE * CELL_SIZE / 2, BOARD_SIZE * CELL_SIZE / 2)
turtle.pendown()
for i in range(BOARD_SIZE + 1):
turtle.forward(BOARD_SIZE * CELL_SIZE)
turtle.right(90)
turtle.forward(CELL_SIZE)
turtle.right(90)
turtle.forward(BOARD_SIZE * CELL_SIZE)
turtle.left(90)
turtle.forward(CELL_SIZE)
turtle.left(90)
turtle.penup()
# 初始化棋子位置
board = [[0] * BOARD_SIZE for i in range(BOARD_SIZE)]
board[BOARD_SIZE//2-1][BOARD_SIZE//2-1] = 1
board[BOARD_SIZE//2][BOARD_SIZE//2] = 1
board[BOARD_SIZE//2-1][BOARD_SIZE//2] = 2
board[BOARD_SIZE//2][BOARD_SIZE//2-1] = 2
# 画棋子
def draw_piece(x, y, color):
turtle.penup()
turtle.goto(x * CELL_SIZE - BOARD_SIZE * CELL_SIZE / 2 + CELL_SIZE / 2,
y * CELL_SIZE - BOARD_SIZE * CELL_SIZE / 2 + CELL_SIZE / 2)
turtle.pendown()
turtle.begin_fill()
turtle.color(color)
turtle.circle(CELL_SIZE / 2 - 5)
turtle.end_fill()
# 判断是否可以下棋
def can_drop_piece(board, column):
if board[0][column] == 0:
return True
else:
return False
# 下棋
def drop_piece(board, column, player):
for row in range(BOARD_SIZE - 1, -1, -1):
if board[row][column] == 0:
board[row][column] = player
return row
return None
# 判断是否有胜者
def get_winner(board):
# 水平方向
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE - 3):
if board[row][col] == board[row][col+1] == board[row][col+2] == board[row][col+3] and board[row][col] != 0:
return board[row][col]
# 垂直方向
for col in range(BOARD_SIZE):
for row in range(BOARD_SIZE - 3):
if board[row][col] == board[row+1][col] == board[row+2][col] == board[row+3][col] and board[row][col] != 0:
return board[row][col]
# 对角线方向
for row in range(BOARD_SIZE - 3):
for col in range(BOARD_SIZE - 3):
if board[row][col] == board[row+1][col+1] == board[row+2][col+2] == board[row+3][col+3] and board[row][col] != 0:
return board[row][col]
for row in range(BOARD_SIZE - 3):
for col in range(3, BOARD_SIZE):
if board[row][col] == board[row+1][col-1] == board[row+2][col-2] == board[row+3][col-3] and board[row][col] != 0:
return board[row][col]
return None
# 初始化玩家
player = 1
# 监听鼠标事件
def on_click(x, y):
global player
column = int((x + BOARD_SIZE * CELL_SIZE / 2) // CELL_SIZE)
if can_drop_piece(board, column):
row = drop_piece(board, column, player)
draw_piece(column, row, "black" if player == 1 else "red")
winner = get_winner(board)
if winner is not None:
turtle.penup()
turtle.goto(-CELL_SIZE * 2, 0)
turtle.pendown()
turtle.write("Player " + str(winner) + " wins!", font=("Arial", 24, "bold"))
else:
player = 2 if player == 1 else 1
# 绑定鼠标事件
turtle.onscreenclick(on_click)
# 主循环
draw_board()
turtle.mainloop()
```
该程序使用了 turtle 的画图功能实现了一个简单的重力四子棋游戏,可以在 8x8 的棋盘上进行两人对战,支持鼠标操作,能够自动判断胜者并显示胜利信息。
阅读全文