【发布时间】:2014-04-04 01:51:16
【问题描述】:
我需要画出我的 x 和 o,这样当我点击一个正方形时,它就会在中间画出它。我听说你可以找到正方形的中点,但我也不知道该怎么做。当我点击 X 和 O 时,我该怎么做才能使它们在方块中间绘制?
import turtle
#I need to fix the positions of the X and O's so that they draw more perfectly into the squares of the board.
class TicTacToe:
def __init__(self):
self.u__init_board = []
def draw_board():
'''draws a tic-tac-toe board over the 9 turtle squares'''
t=turtle.Turtle()
t.ht() # makes the turtle invisable
t.up()
t.goto(-40,-40)
t.down()
t.forward(240)
t.left(90)
t.forward(240)
t.left(90)
t.forward(240)
t.left(90)
t.forward(80)
t.left(90)
t.forward(240)
t.right(90)
t.forward(80)
t.right(90)
t.forward(240)
t.left(90)
t.goto(-40,-40)
t.left(180)
t.forward(160)
t.up()
t.goto(40,-40)
t.down()
t.forward(240)
t.right(90)
t.forward(80)
t.right(90)
t.forward(240)
def setup_board():
'''Creates 3 rows of 3 turtles using range(0, 240, 80); turtle.Turtle(); up(); shape('square'); shapesize(4, 4, 4);
color('white'); goto(x, y). Each turtle is registered to respond to click events using onclick(mark).
Calls draw_grid() once the 9 turtles are on the board.'''
for y in range(0,240,80):
for x in range (0,240,80):
t=turtle.Turtle()
t.up()
t.shape('square')
t.shapesize(4,4,4,)
t.color('white')
t.goto(x,y)
t.onclick(TicTacToe.mark)
TicTacToe.draw_board()
def mark(x, y):
'''Function is invoked whenever a turtle registered to respond to click event is clicked. Creates a turtle and draws
either a circle or an x centered on the x, y coordinates of the click.
Be sure to set circle to False once the circle is drawn and to True once the x is drawn. '''
ct = turtle.Turtle()
ct.ht() #hides the turtle (makes the turtle invisable)
ct.up()
global circle
if circle:
turtle.penup()
#turtle.speed(0)
turtle.goto(x,y)
turtle.down()
turtle.circle(30)
turtle.left(45)
circle = False
else:
turtle.up()
#turtle.speed(0)
turtle.goto(x,y)
turtle.down()
turtle.left(45)
turtle.forward(40)
turtle.left(180)
turtle.forward(80)
turtle.left(180)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
turtle.left(180)
turtle.forward(80)
circle = True
def main():
wn = turtle.Screen()
wn.title('OG Tic Tac Toe')
wn.bgcolor("red")
global circle
circle = False
TicTacToe.setup_board()
return 'Done'
if __name__ == '__main__':
TicTacToe.main()
turtle.TK.mainloop()
【问题讨论】:
-
到一个正方形的左上角,向下(高度/2),向右(宽度/2)。砰! (魔法)
-
我明白了,但是如何将它加入我的代码中?
-
如果
turtle对象以像素为单位移动,为什么不使用勾股定理求对角边的长度。然后让turtle移动那么多像素 -
我在哪里以及如何将其放入我的代码中?
-
你的代码完全被破坏了它在当前状态下什么都不做......如果你需要帮助,请发布你的真实代码
标签: python function class tic-tac-toe turtle-graphics