Bry*_*nta 6 python graphics if-statement simplification modulus
如何简化这个if语句?这是一个加号:http: //i.stack.imgur.com/PtHO1.png
如果语句完成,则在x和y坐标处设置块.
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or y%5 == 3 or y%5 == 4) and \
not(x%5 == 2 and y%5 == 2) and \
not(x%5 == 4 and y%5 == 2) and \
not(x%5 == 2 and y%5 == 4) and \
not(x%5 == 4 and y%5 == 4):
...
Run Code Online (Sandbox Code Playgroud)
Dav*_*ebb 15
这是一样的:
if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1):
Run Code Online (Sandbox Code Playgroud)
mar*_*eau 12
基本上你正在平铺5x5二进制模式.这里有一个明确的表达:
pattern = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 1],
[0, 0, 0, 1, 0]]
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if pattern[x%5][y%5]:
...
Run Code Online (Sandbox Code Playgroud)
这是一种非常简单和通用的方法,可以轻松修改模式.
有两个简单的修复:
x % 5和y % 5in或链接<来测试值:此外,用于测试<= 4(或< 5)实际上是多余的,因为每一个的值lx和ly将<5.
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
lx = x % 5 # for local-x
ly = y % 5 # for local-y
if lx > 1 and y > 1 and \
not (lx == 2 and ly == 2) and \
not (lx == 4 and ly == 2) and \
not (lx == 2 and ly == 4) and \
not (lx == 4 and ly == 4):
Run Code Online (Sandbox Code Playgroud)
或者你可以保留一个实际允许的元组列表:
cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x % 5, y % 5) in cross_fields:
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1676 次 |
| 最近记录: |