Created
April 6, 2013 03:34
-
-
Save forestbelton/5324642 to your computer and use it in GitHub Desktop.
Basic function plotter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame, sys | |
from pygame.locals import * | |
from math import floor | |
import math | |
WIDTH, HEIGHT = 320, 200 | |
pygame.init() | |
pygame.display.set_mode((WIDTH, HEIGHT)) | |
pygame.display.set_caption('Function plotter') | |
screen = pygame.display.get_surface() | |
# Scales values in [a, b] to [c, d]. | |
class Scaler: | |
def __init__(self, a, b, c, d): | |
self.quot = float(d - c) / float(b - a) | |
self.term = -a * self.quot + c | |
def scale(self, x): | |
return x * self.quot + self.term | |
class Window: | |
def __init__(self, scaleX, scaleY): | |
self.scaleX = scaleX | |
self.scaleY = scaleY | |
def scale(self, x, y): | |
return (self.scaleX.scale(x), self.scaleY.scale(y)) | |
def handle_input(events): | |
for event in events: | |
if event.type == QUIT: | |
sys.exit(0) | |
def stepper(a, b, delta): | |
x = a | |
while x <= b: | |
yield x | |
x += delta | |
def get_coords(x, win, func): | |
px, py = win.scale(x, func(x)) | |
return (px, HEIGHT - py) | |
window = Window(Scaler(-10, 10, 0, WIDTH), Scaler(-100, 100, 0, HEIGHT)) | |
while True: | |
screen.fill(Color(255, 255, 255, 0)) | |
pygame.draw.line(screen, Color(0, 0, 0, 0), (WIDTH/2, 0), (WIDTH/2, HEIGHT)) | |
pygame.draw.line(screen, Color(0, 0, 0, 0), (0, HEIGHT/2), (WIDTH, HEIGHT/2)) | |
f = eval('lambda x: ' + raw_input('f(x) = ')) | |
s = stepper(-10, 10, 0.1) | |
last = get_coords(s.next(), window, f) | |
for x in s: | |
px, py = get_coords(x, window, f) | |
if py >= 0 and py < HEIGHT: | |
pygame.draw.line(screen, Color(255, 0, 0, 0), last, (px, py)) | |
last = (px, py) | |
pygame.display.flip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment