【问题标题】:I can't draw all functions with my script我无法用我的脚本绘制所有函数
【发布时间】:2021-11-26 14:37:25
【问题描述】:

我制作了一个脚本,它应该接受用户输入的数学函数 (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

【问题讨论】:

    标签: python math graph charts pygame


    【解决方案1】:

    从函数中创建一个点列表:

    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:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-18
      • 2019-11-01
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多