【问题标题】:How to put the tic-tac-toe grid in centre of the window using python pyglet如何使用 python pyglet 将井字游戏网格放在窗口的中心
【发布时间】:2021-12-09 15:31:56
【问题描述】:
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):
    for i in range(100, 300, 100):
        linex = shapes.Line(i, 1, i, 300, width=10, color=(0, 230, 0), batch=batch)
        linex.opacity = 600
        shape_list.append(linex)
        liney = shapes.Line(1, i, 300, i, 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()

问题是如何使用 pyglet 将网格放在 pyglet 窗口的中心,这个问题就像我脖子上的鱼刺。

【问题讨论】:

    标签: python atom-editor pyglet python-3.9


    【解决方案1】:

    定义offset_xoffset_y 并将其添加到坐标中:

    def drawBoard(shape_list, batch=None):
        offset_x, offset_y = 150, 150
    
        for i in range(offset_x+100, offset_x+300, 100):
            linex = shapes.Line(i, offset_y, i, offset_y+300, width=10, color=(0, 230, 0), batch=batch)
            linex.opacity = 600
            shape_list.append(linex)
        
        for i in range(offset_x+100, offset_x+300, 100):
            liney = shapes.Line(offset_y, i, offset_y+300, i, width=10, color=(0, 230, 0), batch=batch)
            liney.opacity = 600
            shape_list.append(liney)
    

    一种更通用的方法是计算窗口的中心和网格的边界框:

    def drawBoard(shape_list, batch=None):
        window_size = 600, 600
        center = window_size[0]//2, window_size[1]//2
        tile_size = 100
        left, right = center[0] - 1.5*tile_size, center[0] + 1.5*tile_size, 
        bottom, top = center[1] - 1.5*tile_size, center[1] + 1.5*tile_size,
        for i in range(1, 3):
            offset = tile_size * i   
            linex = shapes.Line(left, offset+bottom, right, offset+bottom, width=10, color=(0, 230, 0), batch=batch)
            linex.opacity = 600
            shape_list.append(linex)
            liney = shapes.Line(offset+left, bottom, offset+left, top, width=10, color=(0, 230, 0), batch=batch)
            liney.opacity = 600
            shape_list.append(liney)
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多