Search code examples
pythonatom-editorpygletpython-3.9

How to put the tic-tac-toe grid in centre of the window using python pyglet


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()

Output of the code.

The problem is how can I put the grid in the center of the pyglet window by using pyglet this problem is like a fishbone in my neck.


Solution

  • Define offset_x and offset_y and add it to the cooridantes:

    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)
    

    A more generic way is to compute the center of the window and the bounding box of the grid:

    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)