我想在Python上绘制一个棋盘,但我只得到一个黑色方块。 你能帮我解决一下这个程序吗?
import turtle
def filled_square(size, color, x, y):
turtle.setpos(x, y)
turtle.color(color)
turtle.begin_fill()
for i in range(4):
angle = 90
turtle.fd(size)
turtle.lt(angle)
turtle.end_fill()
turtle.up()
import sys
n = int(sys.argv[1])
s = int(sys.argv[2])
square_size = s//n
y=0
for i in range(n):
x = 0
for j in range(n):
if (i+j)%2==0:
filled_square(square_size, "red", x, y)
else:
filled_square(square_size, "black", x, y)
x+=square_size
turtle.down()
turtle.done()
答案 0 :(得分:1)
y=0
for i in range(n):
x = 0
for j in range(n):
if (i+j)%2==0:
filled_square(square_size, "red", x, y)
else:
filled_square(square_size, "black", x, y)
x+=square_size
在这里遇到问题。
x = 0
for i in range(n):
y=0
for j in range(n):
if (i+j)%2==0:
filled_square(square_size, "red", x, y)
else:
filled_square(square_size, "black", x, y)
y+=square_size
x+=square_size
现在你应该得到你想要的棋盘形状。
替代解决方案:您可以通过根本不具备这些值来避免记账x和y的值的问题。您可以直接从i和j推导出方块的坐标。
for i in range(n):
for j in range(n):
if (i+j)%2==0:
filled_square(square_size, "red", i*square_size, j*square_size)
else:
filled_square(square_size, "black", i*square_size, j*square_size)
在if和else块中合并公共逻辑也可能很好,只能区分实际更改的值(即颜色)
for i in range(n):
for j in range(n):
if (i+j)%2==0:
color = "red"
else:
color = "black"
filled_square(square_size, color, i*square_size, j*square_size)
答案 1 :(得分:0)
您需要增加x和y。另请注意,x应在内循环中递增。这是工作代码,
import turtle
def filled_square(size, color, x, y):
turtle.setpos(x, y)
turtle.color(color)
turtle.begin_fill()
for i in range(4):
angle = 90
turtle.fd(size)
turtle.lt(angle)
turtle.end_fill()
turtle.up()
import sys
n = int(sys.argv[1])
s = int(sys.argv[2])
square_size = s//n
y=0
for i in range(n):
x = 0
for j in range(n):
if (i+j)%2==0:
filled_square(square_size, "red", x, y)
else:
filled_square(square_size, "black", x, y)
x+=square_size
y+=square_size
turtle.down()
turtle.done()
答案 2 :(得分:0)
我建议使用这样的功能编程进行电路板/游戏工作。它将使一切变得更容易维护,并使实现新功能变得更容易。
import turtle
def filled_square(size, color, x, y):
turtle.up()
turtle.setpos(x, y)
turtle.color(color)
turtle.begin_fill()
for i in range(4):
angle = 90
turtle.fd(size)
turtle.lt(angle)
turtle.end_fill()
def board(length, size, x_pos=0, y_pos=0):
for y in range(length):
for x in range(length):
if (x+y)%2==0:
filled_square(
size, "red", (x * square_size) - x_pos, (y * square_size) - y_pos)
else:
filled_square(
size, "black", (x * square_size) - x_pos, (y * square_size) - y_pos)
turtle.done()
关键字参数也很棒。如果您决定添加更多颜色,那么就像添加两个参数一样简单,
def board(length, size, x_pos=0, y_pos=0, color1="red", color2="black"):
for y in range(length):
for x in range(length):
if (x+y)%2==0:
filled_square(
size, color1, (x * square_size) - x_pos, (y * square_size) - y_pos)
else:
filled_square(
size, color2, (x * square_size) - x_pos, (y * square_size) - y_pos)