我正在為我的學校專案優化我的代碼。我正在嘗試使用 Python 圖形庫繪制網格。當我運行回圈時,它會繼續添加行,但 x1 和 x2 值不會像我需要的那樣恢復到它們的原始值。它在行的最后一個正方形的 (x2, y2) 點擴展下一行。任何有關我如何解決此問題的見解將不勝感激!
import random, graphics
from graphics import *
x1 = 5
x2 = 65
y1 = 5
y2 = 65
def make_square(x1, x2, y1, y2):
location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
location.draw(win)
win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))
for i in range(9):
for j in range(9):
make_square(x1, x2, y1, y2)
x1 = x1 60
x2 = x2 60
y1 = y1 60
y2 = y2 60
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done
uj5u.com熱心網友回復:
因此,在開始繪制新行時,您想要重置x1and x2,這是有道理的,因為下一行將從與前一行相同的 x 位置開始。您是否嘗試將您的x1 = 5and添加x2 = 65到外部 for 回圈的開頭,而不是在回圈外定義它們?
這樣看:你y在外回圈之外定義,因為它在行上回圈,你x在內回圈外定義,因為它在列上回圈:
import random, graphics
from graphics import *
def make_square(x1, x2, y1, y2):
location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
location.draw(win)
win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))
y1 = 5
y2 = 65
for i in range(9):
x1 = 5
x2 = 65
for j in range(9):
make_square(x1, x2, y1, y2)
x1 = x1 60
x2 = x2 60
y1 = y1 60
y2 = y2 60
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377539.html
上一篇:如何在python中使用unicode轉義洗掉str變數中的b''前綴?
下一篇:帶復位的Numpy陣列計數器
