擅长:python、mysql、java
<p>对每个坐标使用元组列表,而不是变量。这将大大缩短代码的长度。在</p>
<p><strong>编辑1</strong><br/>
为了使它更短,我使用了<a href="https://mail.python.org/pipermail/python-dev/2005-September/056846.html" rel="nofollow">ternary expressions</a>。在</p>
<p><strong>编辑2</strong><br/>
用一个函数把它再紧一点。我不认为它能变短,但我会看看我能做些什么;)</p>
<pre><code>import pygame
from random import randrange
x = 215
y = 223
step = 50
frame_count = 0
side = True
hike = True
p1 = [(265, 274), (265, 224), (265, 274), (465, 174), (365, 224), (565, 274)]
p2 = [(415, 174), (415, 224), (415, 274), (215, 174), (315, 224), (115, 274)]
frame_count += 1
def move(p):
defense = randrange(len(p))
if frame_count == 45:
if p[defense][0] != x:
p[defense][0] += step if p[defense][0] < x else -step
if p[defense][1] != y:
p[defense][1] += step if p[defense][1] < y else -step
move(p1 if side else p2)
</code></pre>