我试图用Python创建一个棋盘。目前,我已经弄清楚了游戏本身的实际设置,但我想在方格内画圆来创造“游戏”的部分。在
import turtle
turtle.bgcolor("Grey")
def drawRect(color):
iterations = 0
turtle.begin_fill() # Begin the fill process.
turtle.down()
turtle.color(color)
while iterations < 4:
turtle.forward(40)
turtle.left(90)
iterations += 1
turtle.up() # Pen up
turtle.end_fill()
def pushTurtleForward():
turtle.forward(40)
def drawHorizontal(inverted):
if(inverted):
for horizontal in range(0, 8):
if(horizontal > 0 and horizontal % 2 != 0):
pushTurtleForward()
drawRect("white")
if(horizontal > 0 and horizontal % 2 == 0):
pushTurtleForward()
drawRect("black")
if(horizontal == 0):
drawRect("black")
else:
for horizontal in range(0, 8):
if(horizontal > 0 and horizontal % 2 != 0):
pushTurtleForward()
drawRect("black")
if(horizontal > 0 and horizontal % 2 == 0):
pushTurtleForward()
drawRect("white")
if(horizontal == 0):
drawRect("white")
for drawVertical in range(0, 8):
turtle.setx(0)
turtle.sety(40 * drawVertical)
if(drawVertical % 2 == 0):
drawHorizontal(inverted=True)
else:
drawHorizontal(inverted=False)
turtle.setx(0)
turtle.sety(0)
turtle.done()
我在挣扎着在哪里我甚至放了一个圈为比赛抽签?它是否应该是一个单独需要调用的函数?我能把它放在画正方形的环里面吗?在
实际上,一个单独的圆函数是个好主意。 一般来说,对于像棋盘这样的二维物体,最好的方法是在彼此内部使用两个循环(嵌套循环)。外部循环遍历所有8行,对于每一行,内部循环遍历所有8列。同样在
drawRect
中,对while
循环的操作是正确的,但是for
循环更常见。在我强烈建议你不要在方格里画圆圈,而是要创建一只海龟来代表你的跳棋。这将允许你在你的棋盘周围移动棋盘,而不需要删除棋盘格的旧位置和重新绘制空方块。在
我重新编写了您的样式代码,并添加了一个演示部分,其中随机分布了一打关于黑色方块的红色方格:
相关问题 更多 >
编程相关推荐