<p>当语句<code>xPos = xPos + dxPos</code>、<code>yPos = yPos + dyPos</code>时,首先读取变量<code>xPos</code>和<code>yPos</code>,然后添加<code>dxPos</code>和<code>dyPos</code>,最后将结果分配给<code>xPos</code>和<code>yPos</code>。<br/>
第一步,读取失败,因为变量在读取之前没有定义。在主应用程序循环之前定义变量。e、 g:</p>
<pre class="lang-py prettyprint-override"><code>xPos, yPos = 100, 100
main = True
# main loop
while main:
# [...]
</code></pre>
<hr/>
<p>此外,您的应用程序中存在<a href="https://docs.python.org/3/reference/lexical_analysis.html" rel="nofollow noreferrer">Indentation</a>问题。您必须在应用程序循环而不是事件循环中执行逻辑。<br/>
此外,您必须添加<code>dx</code>和<code>dy</code>,而不是<code>dxPos</code>和<code>dyPos</code></p>
<pre class="lang-py prettyprint-override"><code># set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type == pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
# INDENTATION
#< |
xPos = xPos + dx
yPos = yPos + dy
if x >= 750:
dx = -abs(dx)
color = random_color()
elif x <=50:
dx = abs(dx)
color = random_color()
if y <= 50:
dy = abs(dy)
color = random_color()
elif y >=550:
dy = -abs(dy)
color = random_color()
if x2 >= 775:
dx2 = -abs(dx2)
color2 = random_color()
elif x2 <= 25:
dx2 = abs(dx2)
if y2 <= 25:
dy2 = abs(dy2)
color2 = random_color()
elif y2 >= 575:
dy2 = -abs(dy2)
color2 = random_color()
if x3 >=700:
dx3 = -abs(dx3)
color3 = random_color()
elif x3 <= 100:
dx3 = abs(dx3)
color3 = random_color()
if y3 <= 100:
dy3 = abs(dy3)
color3 = random_color()
elif y3 >= 500:
dy3 = -abs(dy3)
color3 = random_color()
</code></pre>