Python中的Tic Tac Toe(图形窗口)

时间:2012-12-06 22:04:50

标签: python tic-tac-toe

我必须写的程序不是通用的tic tac toe,而是用户可以决定窗口大小和每边多少个方块。

我无法让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()

0 个答案:

没有答案