You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Pyglet将井字棋网格放置在窗口中心

问题根源

你当前的井字棋网格仅绘制在坐标范围 [1, 300](x轴、y轴均为此区间),而Pyglet窗口的坐标原点默认在左下角,600*600的窗口下该区域刚好对应左下角四分之一区域,所以没有居中。

修改方法

给所有网格线的坐标增加居中偏移量即可,计算逻辑为:

  • 网格总尺寸固定为300300,窗口尺寸为600600,因此水平和垂直方向的偏移量均为 (600 - 300) / 2 = 150
  • 所有网格线的x坐标增加150,y坐标也增加150,就能让整个网格对齐窗口中心

修改后的完整代码如下:

import pyglet
from pyglet import shapes

title = " Tic-tac-toe "

window = pyglet.window.Window(600,600, title)
batch = pyglet.graphics.Batch()

def drawBoard(shape_list, batch=None):
    # 计算居中偏移量,后续改窗口尺寸也能自动适配
    grid_size = 300
    offset_x = (window.width - grid_size) // 2
    offset_y = (window.height - grid_size) // 2
    for i in range(100, 300, 100):
        # 竖线坐标增加偏移
        linex = shapes.Line(i + offset_x, offset_y, i + offset_x, offset_y + grid_size, width=10, color=(0, 230, 0), batch=batch)
        linex.opacity = 600
        shape_list.append(linex)
        # 横线坐标增加偏移
        liney = shapes.Line(offset_x, i + offset_y, offset_x + grid_size, i + offset_y, width=10, color=(0, 230, 0), batch=batch)
        liney.opacity = 600
        shape_list.append(liney)

shape_list = []
drawBoard(shape_list, batch=batch)

@window.event
def on_draw():
    window.clear()
    batch.draw()

pyglet.app.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:36:00