我制作了一個腳本,它應該接受用戶輸入的數學函式 (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
uj5u.com熱心網友回復:
從函式創建一個點串列:
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))
使用以下命令在應用程式回圈中繪制曲線
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367020.html
