You need to enable JavaScript to run this app. 咨询基于turtle的Python四子棋代码将圆形图形改为正方形的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

咨询基于turtle的Python四子棋代码将圆形图形改为正方形的实现方法

四子棋圆形改正方形的实现方案

核心约束:完全保留原有落子判定、位置计算、回合切换、网格布局的逻辑,仅替换图形绘制实现,不修改任何影响游戏规则的代码。

实现思路

原代码使用turtle.dot(40, 颜色)绘制直径40的圆形,该方法的绘制中心为当前海龟所在坐标,绘制范围为中心上下左右各延伸20像素。我们将其替换为同尺寸的实心正方形:以原坐标为正方形中心,边长严格设为40,保证和原圆形的视觉占比、边距完全一致,不会出现布局错位的问题。

具体改动

  • 新增一个通用的中心实心正方形绘制函数,避免重复代码
  • 替换grid()函数中原白色圆形占位的绘制逻辑,调用新的正方形绘制方法
  • 替换tap()函数中原落子彩色圆形的绘制逻辑,调用同一个正方形绘制方法
  • 其余所有代码(网格绘制、点击位置计算、行计数、回合切换、窗口初始化)完全保留,不做任何修改

修改后完整可运行代码

from turtle import *
from freegames import line

# 新增:中心实心正方形绘制函数
def draw_square(cx, cy, size, fill_color):
    half = size / 2
    up()
    goto(cx, cy)
    begin_fill()
    color(fill_color)
    # 移动到正方形左上角
    goto(cx - half, cy + half)
    down()
    # 依次绘制四条边完成正方形
    goto(cx + half, cy + half)
    goto(cx + half, cy - half)
    goto(cx - half, cy - half)
    goto(cx - half, cy + half)
    up()
    end_fill()

turns = {'red': 'yellow', 'yellow': 'red'}
state = {'player': 'yellow', 'rows': [0] * 8}

def grid():
    "Draw Connect Four grid."
    bgcolor('light blue')

    for x in range(-150, 200, 50):
        line(x, -200, x, 200)

    for x in range(-175, 200, 50):
        for y in range(-175, 200, 50):
            # 原dot(40, 'white')替换为正方形绘制
            draw_square(x, y, 40, 'white')

    update()

def tap(x, y):
    "Draw red or yellow square in tapped row."
    player = state['player']
    rows = state['rows']

    row = int((x + 200) // 50)
    count = rows[row]

    x = ((x + 200) // 50) * 50 - 200 + 25
    y = count * 50 - 200 + 25

    # 原dot(40, player)替换为正方形绘制
    draw_square(x, y, 40, player)
    update()

    rows[row] = count + 1
    state['player'] = turns[player]

setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(tap)
done()

效果说明

  • 所有原圆形(棋盘白色占位、红/黄落子标识)会被替换为等尺寸的正方形,和原网格的间距、视觉大小完全匹配
  • 点击选列、落子堆叠顺序、玩家回合切换的逻辑和原代码完全一致,没有任何改动
  • 不需要安装额外依赖,完全基于现有turtle、freegames库运行

内容的提问来源于stack exchange,提问作者Noname

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 00:45:05