2

我必须编写的程序不是通用的井字游戏,而是用户可以决定窗口大小和每边有多少个正方形。

我无法让 X 和 O 显示在每个正方形的中心。我可以得到正确数量的 X 和 O 以相对于正方形的数量出现,但不能让它们显示在每个正方形的中心。这是我到目前为止所拥有的

from graphics import *

import sys


def tic_tac_toe_o(win, center):
    '''
    Circle the winner's photo
    Parameters:
    - win: the window
    - winner_center: the center of the winner's picture (as a Point)
    '''
    outline_width = 5
    circle = Circle(center, boxsize/2)
    circle.setOutline('red')
    circle.setWidth(outline_width)
    circle.draw(win)


def tic_tac_toe_x(win, p1x, p1y):
    '''
    Cross out the loser's photo
    Parameters:
    - win: the window
    - loser_center: the center of the loser's picture (as a Point)
    '''
    for i in range(2):
        deltaX = (-1) ** i * (boxsize / 2)
        deltaY = (boxsize / 2)
        line = Line(Point(p1x - deltaX, p1y - deltaY),
                 Point(p1x + deltaX, p1y + deltaY))
        line.setFill('red')
        line.setWidth(5)
        line.draw(win)



def main():


    global win
    global boxsize

    try:
        windowsize = int(input("Size of window to draw?: "))
        if windowsize < 100 or windowsize > 2000:
            print("Error: invalid window size")
            quit()

        squares = int(input("How many squares per side?: "))
        boxsize = windowsize/ squares
        if squares < 3 or squares > windowsize / 10:
            print("Error: invalid number")
            quit()
    except ValueError:
        sys.exit("not a valid number")

    win = GraphWin("Tic Tac Toe", windowsize, windowsize)

    for i in range(squares - 1):
        hline = Line(Point(0, (windowsize/squares) * (i + 1)), Point(windowsize,  (windowsize/squares) * (i + 1)))
        hline.draw(win)
        vline = Line(Point((windowsize/squares) * (i + 1), 0), Point((windowsize/squares) * (i + 1), windowsize))
        vline.draw(win)




    for i in range((squares ** 2) // 2):

        print("Player 1: click a square.")
        p1mouse = win.getMouse()
        p1x = p1mouse.getX()
        p1y = p1mouse.getY()
        tic_tac_toe_x(win, p1x, p1y)

        print("Player 2: click a square.")
        p2mouse = win.getMouse()
        p2x = p2mouse.getX()
        p2y = p2mouse.getY()
        tic_tac_toe_o(win, Point(p2x, p2y))

    if squares % 2 == 1:
        print("Player 1: click a square.")
        p1mouse = win.getMouse()
        p1x = p1mouse.getX()
        ply = p1mouse.getY()
        tic_tac_toe_x(win, p1x, p1y)

main()
4

0 回答 0