问题: 怎么才能让我的项目代码更少呢, 这个hangman图形的定义代码太多了
def joonista_mees(valede_pakkumiste_arv):
if valede_pakkumiste_arv == 0:
ht()
up()
right(90)
forward(150)
right(90)
forward(30)
right(180)
down()
forward(200)
back(170)
left(90)
forward(150)
right(90)
forward(100)
right(90)
if valede_pakkumiste_arv == 1:
forward(15)
right(90)
circle(15)
left(90)
up()
forward(30)
down()
if valede_pakkumiste_arv == 2:
forward(45)
backward(45)
right(45)
forward(20)
backward(20)
left(90)
if valede_pakkumiste_arv == 3:
forward(20)
backward(20)
right(45)
forward(45)
right(30)
if valede_pakkumiste_arv == 4:
forward(45)
backward(45)
left(60)
if valede_pakkumiste_arv == 5:
forward(45)
backward(45)
right(30)
up()
backward(67)
if valede_pakkumiste_arv == 6:
right(90)
forward(3)
right(45)
down()
forward(3)
backward(6)
forward(3)
right(90)
forward(3)
backward(6)
forward(3)
right(45)
up()
forward(6)
left(45)
down()
forward(3)
backward(6)
forward(3)
right(90)
forward(3)
backward(7)
有什么方法可以让代码更紧凑呢? 或许可以把一些代码写进同一行?
回答: 你可以写一个小解释器作为一种迷你语言
比如,你可以把
forward(3)
right(90)
forward(3)
backward(7)
编码进字符串,像这样dostring = "f 3 r 90 f 3 b 7"
,
它的解释器可以这样编写:
def interpret( dostring ):
tokens = dostring.split()
for command_id in range(0, len(tokens), 2):
command = tokens[command_id]
param = int(tokens[command_id+1])
if command == "f":
forward( param )
elif command == "b":
backward( param )
elif command == "r":
right(param)
else:
print("Unknown command: %s" % command)
然后, 只需这样调用interpret("f 3 r 90 f 3 b 7")