Python 这只打印n=8的完美棋盘,否则它会在从一行切换到另一行时打印斜线
谁能告诉我哪里出了错 如果你试着把n=5,你就会明白我的意思 这只适用于n=8 提前感谢这应该可以:Python 这只打印n=8的完美棋盘,否则它会在从一行切换到另一行时打印斜线,python,python-3.x,Python,Python 3.x,谁能告诉我哪里出了错 如果你试着把n=5,你就会明白我的意思 这只适用于n=8 提前感谢这应该可以: import turtle import sys turtle.speed(0) n=int(sys.argv[1]) def filled_square(size, color, x, y): print((change_color-x)%(n+1)==0) if (change_color-x)%(n+1)==0: turtle.up() turtle
import turtle
import sys
turtle.speed(0)
n=int(sys.argv[1])
def filled_square(size, color, x, y):
print((change_color-x)%(n+1)==0)
if (change_color-x)%(n+1)==0:
turtle.up()
turtle.setpos(x+size*b,y+size*c)
turtle.down()
turtle.color(color)
turtle.begin_fill()
for i in range(4):
turtle.fd(size)
turtle.rt(90)
turtle.end_fill()
color=['nothing','black','red']
change_color=n
c=0
x=0
for i in range(n):
b=0
for j in range(n):
a=-1
a=a**change_color
filled_square(200/n, color[a], -100, 100)
change_color+=1
b+=1
c-=1
x+=1
change_color+=1
turtle.done()
我对你的代码进行了一些重构。至关重要的是,直接从for循环中提取x和y非常容易。此外,在函数中引用假定的全局变量可能会非常混乱,因此实际的x
和y
现在是平方函数的参数。我试图忠实于您代码的方法,但更改了a
的表达式。它现在检查x
或y
中是否有一个是奇数(使用按位and和按位xor运算符。按位and的作用类似于此处的%2
)-最好将其写成
import turtle
import sys
turtle.speed(0)
def filled_square(size, color, cx, cy, x, y):
turtle.up()
turtle.setpos(cx + size * x, cy + size * y)
turtle.down()
turtle.color(color)
turtle.begin_fill()
for i in range(4):
turtle.fd(size)
turtle.rt(90)
turtle.end_fill()
def checkerboard(n):
color=['black','red']
for x in range(n):
for y in range(n):
a = (x & 1) ^ (y & 1)
filled_square(200/n, color[a], -100, -100, x, y)
turtle.done()
if __name__ == "__main__":
checkerboard(int(sys.argv[1]))
这比试图从算术语句生成索引要清晰得多。首先感谢您的回答,其次我需要棋盘的大小保持不变,无论它由多少个正方形组成@伊扎克万Dongen@John我很确定棋盘的大小是一样的。。你是说正方形的大小吗?
if (x & 1) ^ (y & 1):
turtle.color("red")
else:
turtle.color("black")