我正在
Traceback (most recent call last): File "H:\Documents\game.py", line 73, in <module> if attemptThis[i] != target[i]: IndexError: string index out of range Press any key to continue . . .
运行此代码时出现错误。
#-----------------------------------------------------
# Python 'Evolution of Text' Program
# More programs at: usingpython.com/programs
#-----------------------------------------------------
possibleCharacters = string.ascii_uppercase + ' .!?;:='
target = """
lMMMMMMMM .MMMM= MMM MMM
lMM MMl M=M MMM =MM MMM
lMM M=. MMM M=M= M=MM=MM =M===== M=MMMM= M=M MM=MMM==l ==M===M= MMM MMMM =M=MM==MM
lMM M=. MMM== MMM .== ==M.... =l= l===l=M. MMM .MMM MMM= MMM
lMM====== MMM MM======== ......=ll .....MMl lll =MM =MM l==....M=M =MM MMM
lM= M=M M=====M =====M=M =======MM .M===MMM MMM =M====MMM MMM MMM
"""
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
if generation == 1000:
break
generation += 1
attemptThis = attemptNext
我在这里找到了此代码,并对其进行了修改以供自己使用。在添加退出子句之前,它一直在工作
if generation == 1000:
break
之所以添加,是因为生成ASCII花费了我很多时间。我正在将其用作正在处理的小项目中的标题屏幕,因此修复此问题并不是至关重要的,因为我总是可以回到使用Print """Text Here"""
命令来代替。
直接在集合上循环而不是使用索引是更pythonic的。由于我对您的程序应该执行的操作感到好奇,因此我也重写了其他部分以使其运行。
import time, random, string
target = """
lMMMMMMMM
lMM MMl
lMM M=. MMM M=M= M=MM=MM =M===== M=MMMM=
lMM M=. MMM== MMM .== ==M.... =l=
lMM====== MMM MM======== ......=ll .....MMl
lM= M=M M=====M =====M=M =======MM
.MMMM= MMM MMM
M=M MMM =MM MMM
M=M MM=MMM==l ==M===M= MMM MMMM =M=MM==MM
l===l=M. MMM .MMM MMM= MMM
lll =MM =MM l==....M=M =MM MMM
.M===MMM MMM =M====MMM MMM MMM
"""
chars = list(set(target + string.ascii_uppercase) - {'\n'})
attempt = ''.join('\n' for c in target)
# First attempt is just a bunch of newlines. This makes the
# text alignment correct after the first run through the loop
while target != attempt:
attempt = ''.join(
tc if tc == ac else random.choice(chars)
for tc, ac in zip(target, attempt)
)
clearscreen = '\033c' # linux terminal control character
print(clearscreen + attempt)
time.sleep(0.05)
这是它的外观预览(链接到asciinema.org)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句