无法解决此递增和递减问题

时间:2020-01-20 20:35:40

标签: python python-3.x

我正在做一个python练习,我必须将圆圈从50px减小到10px。达到10像素后,圆圈必须扩展回50像素。我现在陷入困境,因为我能够将圆圈从50px缩小到10px,但是当我尝试将其扩展回50px时,它陷入了10-11px。

代码如下:

import simplegui

WIDTH = 100
HEIGHT = 100
RADIUS = 50
color = 'Green'
iterations = 0

def draw_handler(canvas):
    global iterations, RADIUS, size_reach
    iterations += 1
    canvas.draw_circle((100, 100), RADIUS, 1, color, color)
    if(iterations%6==0):
        if(RADIUS!=10):
            RADIUS-=1
            print("1st: " + str(RADIUS))
        elif(RADIUS == 10):
            if(RADIUS!=50):
                RADIUS+=1
                print("2nd: " + str(RADIUS))

frame = simplegui.create_frame('Testing', WIDTH*2, HEIGHT*2)
frame.set_draw_handler(draw_handler)
frame.start()

感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您必须保留指示当前方向的状态变量。

color = 'Green'
WIDTH = 100
HEIGHT = 100
MIN_RADIUS = 10
MAX_RADIUS = 50

iterations = 0
direction = -1
radius = 50


def draw_handler(canvas):
    global iterations, radius, direction
    iterations += 1
    canvas.draw_circle((WIDTH / 2, HEIGHT / 2), radius, 1, color, color)
    radius = radius + direction
    if direction < 0 and radius <= MIN_RADIUS:
        print(f'iterations={iterations}, radius={radius}')
        direction = 1
    if direction > 0 and radius >= MAX_RADIUS:
        print(f'iterations={iterations}, radius={radius}')
        direction = 0  # done