Created
May 17, 2014 21:16
-
-
Save Informatic/3d12033cc58463bfe087 to your computer and use it in GitHub Desktop.
Random rotating cube in terminal with some abstracted graphics class
This file contains 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
# -*- coding: utf-8 -*- | |
import sys, time, math, atexit, select | |
class Screen(object): | |
def __init__(self, width=80, height=24): | |
self.output = sys.stdout | |
atexit.register(self.clear) | |
# FIXME: don't flush on every escapecode | |
def _e(self, s): | |
self.output.write('\x1b['+s) | |
self.output.flush() | |
def point(self, x, y, c="■"): | |
self.goto(x, int(y/2)) | |
self.output.write(c) | |
self.output.flush() | |
def color(self, color): | |
self._e("%sm" % color) | |
def goto(self, x, y): | |
self._e("%s;%sH" % (y+1, x+1)) | |
def clear(self): | |
self._e("2J") | |
self._e(";H") | |
# wikipedia: Bresenham's line algorithm | |
# http://snipplr.com/view/22482/ | |
def line(self, x, y, x2, y2): | |
steep = 0 | |
dx = abs(x2 - x) | |
if (x2 - x) > 0: sx = 1 | |
else: sx = -1 | |
dy = abs(y2 - y) | |
if (y2 - y) > 0: sy = 1 | |
else: sy = -1 | |
if dy > dx: | |
steep = 1 | |
x,y = y,x | |
dx,dy = dy,dx | |
sx,sy = sy,sx | |
d = (2 * dy) - dx | |
for i in range(0,dx): | |
if steep: self.point(y,x) | |
else: self.point(x,y) | |
while d >= 0: | |
y = y + sy | |
d = d - (2 * dx) | |
x = x + sx | |
d = d + (2 * dy) | |
self.point(x2,y2) | |
def text(self, t, x, y): | |
self.goto(x, y) | |
self.output.write(t) | |
self.output.flush() | |
if __name__ == '__main__': | |
s = Screen() | |
#s.point(1,1) | |
#s.point(5, 5) | |
h = 20.0 | |
v = [ | |
[-h, -h, -h], | |
[ h, -h, -h], | |
[ h, h, -h], | |
[-h, h, -h], | |
[-h, -h, h], | |
[ h, -h, h], | |
[ h, h, h], | |
[-h, h, h] | |
] | |
c = ((0, 1, 31), (1, 2, 31), (2, 3, 31), (3, 0, 31), (0, 4, 34), (1, 5, 34), (2, 6, 34), (3, 7, 34), (4, 5, 32), (5, 6,32), (6, 7,32), (7, 4,32)) | |
E = 100 * math.tan(2*math.pi/3) | |
def to2d(p): return p[0] * E / (p[2]+E), p[1] * E / (p[2]+E) | |
s.color(31) | |
while True: | |
s.clear() | |
for p in c: | |
x1, y1 = to2d(v[p[0]]) | |
x2, y2 = to2d(v[p[1]]) | |
if len(p) == 3: | |
s.color(p[2]) | |
else: | |
s.color(0) | |
s.line(int(x1+40), int(y1+40), int(x2+40), int(y2+40)) | |
for vec in v: | |
#print vec | |
angle = 0.1 | |
nv0 = math.cos(angle) * vec[0] + math.sin(angle) * vec[2] | |
nv2 = -math.sin(angle) * vec[0] + math.cos(angle) * vec[2] | |
vec[0] = nv0 | |
vec[2] = nv2 | |
angle = 0.05 | |
nv1 = math.cos(angle) * vec[1] - math.sin(angle) * vec[2] | |
nv2 = math.sin(angle) * vec[1] + math.cos(angle) * vec[2] | |
vec[1] = nv1 | |
vec[2] = nv2 | |
time.sleep(0.05) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment