下面的程序允许我用鼠标和键在一个小盒子里创建形状。我在理解下面两条代码时遇到了困难。在
从下面的代码中,当在第一个if语句(与下一个elif语句for-)中按+键时,python如何更改大小?此外,当连续多次按下+按钮时,大小如何增加。嵌套在下面语句中的if语句不应允许由于最后一个\u键而改变大小!=“+”:错误,因为按“+键一次后,该值将存储为最后一个_键。我已经看了一会儿了,但似乎不太明白。在def main():
size = INITIAL_SIZE # current diameter of circle or length of square
set_fill_color(1, 0, 0) # shapes are initially red
last_key = "" # no key pressed yet
drawing_circle = False # are we drawing circles?
drawing_square = False # are we drawing squares?
mouse_was_down = False # was the mouse button most recently down?
while not window_closed():
if is_key_pressed("+"): # increase size?
if last_key != "+":
size = min(size + SIZE_CHANGE, MAX_SIZE)
last_key = "+"
elif is_key_pressed("-"): # decrease size?
if last_key != '-':
size = max(size - SIZE_CHANGE, MIN_SIZE)
last_key = '-'
elif is_key_pressed("r"): # draw in red?
set_fill_color(1, 0, 0)
last_key = "r"
elif is_key_pressed("g"): # draw in green?
set_fill_color(0, 1, 0)
last_key = "g"
elif is_key_pressed("b"): # draw in blue?
set_fill_color(0, 0, 1)
last_key = "b"
elif is_key_pressed("c"): # draw circles?
drawing_circle = True
drawing_square = False
last_key = "c"
elif is_key_pressed("s"): # draw squares?
drawing_circle = False
drawing_square = True
last_key = "s"
else:
last_key = "" # no key pressed
if mouse_down():
if not mouse_was_down: # beginning of a mouse click?
if drawing_circle:
draw_circle(mouse_x(), mouse_y(), size/2)
elif drawing_square:
draw_rectangle(mouse_x() - size/2, mouse_y() - size/2, size, size)
mouse_was_down = True
else:
mouse_was_down = False
request_redraw()
sleep(0.05)
启动图形(主)