我无法用我的脚本绘制所有函数

I can't draw all functions with my script

我制作了一个脚本,它应该接受用户输入的数学函数 (f(x)=...) 并绘制它。我为此使用了 pygame,因为我想在游戏中使用该机制。

我不得不 运行 一次函数的代码,一次没有任何输出,但在那之后,它完美地工作 这是代码:

import pygame


def replace_x(function):
    f = lambda x: eval(function)
    return f


def convert_y(y_coords):
    y_coords = 540 - y_coords
    return y_coords


def convert_x(x_coord):
    x_coord = x_coord + 960
    return x_coord


# variables
background_colour = (255, 255, 255)
screen = pygame.display.set_mode((1920, 1080))
running = True
current_y = 0
previous_y = 0

pygame.init()
pygame.display.set_caption('Mathe Kreativarbeit')

screen.fill(background_colour)

pygame.display.flip()
function_input = input("Funktion: ")
function_input = function_input.replace("^", "**")
pygame.display.flip()

for x_coords in range(-15, 17):
    f = replace_x(function_input)
    current_y = convert_y(f(x_coords))
    previous_y = convert_y(f(x_coords - 1))
    start_pos = (convert_x((x_coords - 1) * 60), previous_y)
    end_pos = (convert_x(x_coords * 60), current_y)
    print(start_pos)
    print(end_pos)
    pygame.draw.aaline(screen, (0, 0, 0), start_pos, end_pos)

    pygame.display.flip()

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

从函数创建点列表:

f = replace_x(function_input)
pt_list = []
for x in range(-20, 20):
    pt_list.append((x, f(x)))

要么打印点列表:

print(pt_list)

或循环打印列表:

for pt in pt_list:
    print(pt)

从点列表创建屏幕坐标列表:

coord_list = []
for pt in pt_list:
    x = round(convert_x(pt[0] * 20))
    y = round(convert_y(pt[1]))
    coord_list.append((x, y))

pygame.draw.aalines()在应用循环中绘制曲线:

clock = pygame.time.Clock()
running = True
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.draw.aalines(screen, (0, 0, 0), False, coord_list)
    pygame.display.flip()

pygame.quit()

输入示例 x**3: