使用Turtle

时间:2018-04-11 20:45:43

标签: python turtle-graphics

这是用于Python的额外信用分配。我已经完成了大部分工作,直到最后一部分,我必须确定所选择的tictactoe盒的面积。

编辑:更新,我只能检测对角线框,用于组合下面的代码回复。 我可以检测到这3个盒子,但其余的仍显示为无,大多数逻辑与循环一起使用,所以我可以理解我哪里出错了。

import turtle
from time import sleep
import sys

CURSOR_SIZE = 20
SQUARE_SIZE = 99
FONT_SIZE = 40
FONT = ('Arial', FONT_SIZE, 'bold')
BOXES = {}
# TRACK BOX
pen = turtle.Turtle()
pen.penup()

def mouse(x, y):
    print('|--------------X={0} Y={1}--------------|'.format(x, y))
    for key in BOXES:
        minx, miny, maxx, maxy = BOXES[key]
        print(key, BOXES[key])
        if (minx <= x <= maxx) and (miny <= y <= maxy):
            print("Found", key)
            return key
    print('None')
    return None  # Not found.

class TicTacToe:
    global BOXES
    def __init__(self):
        # CREATES 2D LIST FOR INTERROGATION
        self.board = [['?'] * 3 for i in range(3)]

    def minmax(self, points):
        """ Find extreme x and y values in a list of 2-D coordinates. """
        minx, miny, maxx, maxy = points[0][0], points[0][1], points[0][0], points[0][1]
        for x, y in points[1:]:
            if x < minx:
                minx = x
            if y < minx:
                miny = y
            if x > maxx:
                maxx = x
            if y > maxy:
                maxy = y
        return minx, miny, maxx, maxy


    def drawBoard(self):
        ##############################################
        turtle.shape('square')
        turtle.shapesize(SQUARE_SIZE * 3 / CURSOR_SIZE)
        turtle.color('black')
        turtle.stamp()
        turtle.hideturtle()
        ##############################################
        for j in range(3):
            for i in range(3):
                # CREATES SHAPE AND STORES IN PLACEHOLDER
                turtle.shape('square')
                box = turtle.shape('square')
                # CREATES SHAPE SIZE AND STORES IN PLACEHOLDER
                turtle.shapesize(SQUARE_SIZE / CURSOR_SIZE)
                boxsize = turtle.shapesize()
                # CREATES SHAPE COLOR
                turtle.color('white')
                turtle.penup()
                # CREATES SHAPE POS AND STORES IN PLACEHOLDER
                turtle.goto(i * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2), j * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2))
                boxpos = turtle.pos()

                mypos = []

                pen.goto(boxpos[0]-50,boxpos[1]+50)
                ##############################################
                for line in range(0, 4):
                    pen.forward(SQUARE_SIZE)
                    pen.right(90)
                    mypos.append(pen.pos())
                turtle.showturtle()
                turtle.stamp()
                ##############################################
                a = mypos[0]
                b = mypos[1]
                c = mypos[2]
                d = mypos[3]
                self.board[j][i] = [a, b, c, d]
        ##############################################
        BOXES['BOX01'] = self.minmax(self.board[0][0])
        BOXES['BOX02'] = self.minmax(self.board[0][1])
        BOXES['BOX03'] = self.minmax(self.board[0][2])
        ##############################################
        BOXES['BOX11'] = self.minmax(self.board[1][0])
        BOXES['BOX12'] = self.minmax(self.board[1][1])
        BOXES['BOX13'] = self.minmax(self.board[1][2])
        ##############################################
        BOXES['BOX21'] = self.minmax(self.board[2][0])
        BOXES['BOX22'] = self.minmax(self.board[2][1])
        BOXES['BOX23'] = self.minmax(self.board[2][2])
        ##############################################
        turtle.onscreenclick(mouse)

turtle.setup(800, 600)
wn = turtle.Screen()
z = TicTacToe()
z.drawBoard()
turtle.mainloop()

2 个答案:

答案 0 :(得分:2)

我相信你没有充分利用Python龟,使问题变得更加困难。点击屏幕时,不要试图在电路板内找到一个正方形,而是让电路板的方块成为响应鼠标点击的乌龟。然后,就位置而言,没有什么可以解决的。

这是一个绘制棋盘的重新实现,允许您点击它,交替地将点击的部分设置为&#39; X&#39;或者&#39; O&#39;:

from turtle import Turtle, Screen

CURSOR_SIZE = 20
SQUARE_SIZE = 50
FONT_SIZE = 40
FONT = ('Arial', FONT_SIZE, 'bold')

class TicTacToe:
    def __init__(self):
        self.board = [['?'] * 3 for i in range(3)] # so you can interrogate squares later
        self.turn = 'X'

    def drawBoard(self):
        background = Turtle('square')
        background.shapesize(SQUARE_SIZE * 3 / CURSOR_SIZE)
        background.color('black')
        background.stamp()
        background.hideturtle()

        for j in range(3):
            for i in range(3):
                box = Turtle('square', visible=False)
                box.shapesize(SQUARE_SIZE / CURSOR_SIZE)
                box.color('white')
                box.penup()
                box.goto(i * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2), j * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2))
                box.showturtle()
                box.stamp()  # blank out background behind turtle (for later)

                self.board[j][i] = box
                box.onclick(lambda x, y, box=box, i=i, j=j: self.mouse(box, i, j))

    def mouse(self, box, i, j):
        box.onclick(None)  # disable further moves on this square

        # replace square/turtle with (written) X or O
        box.hideturtle()
        box.color('black')
        box.sety(box.ycor() - FONT_SIZE / 2)
        box.write(self.turn, align='center', font=FONT)

        self.board[j][i] = self.turn  # record move

        self.turn = ['X', 'O'][self.turn == 'X']  # switch turns

screen = Screen()

game = TicTacToe()

game.drawBoard()

screen.mainloop()

您可以使用board进行评分,或实施智能电脑播放器,或任何您想要的内容。

enter image description here

答案 1 :(得分:0)

这应该为您提供基本思路,即计算每个框的最小和最大x和y值,并将它们存储在BOXES中。这样可以很容易地确定传递给x回调函数的给定ymouse()坐标是否在其中任何一个。

如果您的真实代码中包含多个框,请务必将新的minmax()函数应用到每个代码的角落。

import turtle

""" This will be based off 1 box  instead of all 9"""
pen = turtle.Turtle()
corners = []
BOXES = {}

for line in range(0, 4):
    pen.forward(50)
    pen.left(90)
    corners.append(pen.pos())

def minmax(points):
    """ Find extreme x and y values in a list of 2-D coordinates. """
    minx, miny, maxx, maxy = points[0][0], points[0][1], points[0][0], points[0][1]
    for x, y in points[1:]:
        if x < minx:
            minx = x
        if y < minx:
            miny = y
        if x > maxx:
            maxx = x
        if y > maxy:
            maxy = y
    return minx, miny, maxx, maxy


BOXES['MIDDLEBOX'] = minmax(corners)

for i in BOXES:
    print(i, BOXES[i])
"""
    POINTS FROM LEFT TO RIGHT
    (1) - TOP LEFT CORNER
    (2) - BOTTOM LEFT CORNER
    (3) - BOTTOM RIGHT CORNER
    (4) - TOP RIGHT CORNER
"""

def mouse(x, y):
    """ Return key of box if x, y are within global BOXES
        or None if it's not.
    """
    for key in BOXES:
        minx, miny, maxx, maxy = BOXES[key]
        if (minx <= x <= maxx) and (miny <= y <= maxy):
            print(key)
            return key
    print('None')
    return None  # Not found.

turtle.onscreenclick(mouse)
turtle.mainloop()