Last active
October 19, 2019 08:30
-
-
Save HexDecimal/0b4a076e5fb2cfb4b5ac07b8175c6490 to your computer and use it in GitHub Desktop.
Starfield visualization (python-tcod)
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
#!/usr/bin/env python3 | |
# To the extent possible under law, the Kyle Stewart has waived all | |
# copyright and related or neighboring rights for starfield.py. This work is | |
# published from: United States. | |
# https://creativecommons.org/publicdomain/zero/1.0/ | |
import random | |
import math | |
import tcod | |
import tcod.event | |
import numpy as np | |
WIDTH, HEIGHT = 60, 40 | |
class Dot(): | |
def __init__(self): | |
self.reset() | |
for _ in range(random.randint(0, 150)): | |
self.step() | |
def reset(self): | |
self.pos = (40, 60) | |
direction = random.uniform(0, math.tau) | |
speed = random.uniform(.0001, 0.001) | |
self.speed = math.sin(direction) * speed, math.cos(direction) * speed | |
post = random.uniform(0, 50) | |
self.pos = self.pos[0] + math.sin(direction) * post, self.pos[1] + math.cos(direction) * post | |
def step(self): | |
self.pos = self.pos[0] + self.speed[0], self.pos[1] + self.speed[1] | |
self.speed = self.speed[0] * 1.5, self.speed[1] * 1.5 | |
if not (0 <= self.pos[0] < HEIGHT * 2 and 0 <= self.pos[1] < WIDTH * 2): | |
self.reset() | |
def draw(self, pad): | |
line = np.array(tcod.line_where( | |
round(self.pos[0]), round(self.pos[1]), round(self.pos[0] + self.speed[0]), round(self.pos[1] + self.speed[1]))).T[:-1].T | |
line = line.T[line[0] < HEIGHT * 2].T | |
line = line.T[line[1] < WIDTH * 2].T | |
line = line.T[line[0] >= 0].T | |
line = line.T[line[1] >= 0].T | |
if not line.size: | |
return | |
vis = 255 | |
pad[tuple(line)] |= np.linspace(vis // 2, vis, line.shape[1], dtype=np.uint8)[:, np.newaxis] | |
def main(): | |
"""Example program for tcod.event""" | |
TITLE = None | |
tcod.console_set_custom_font( | |
"data/fonts/consolas10x10_gs_tc.png", tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD | |
) | |
with tcod.console_init_root( | |
WIDTH, | |
HEIGHT, | |
TITLE, | |
order="F", | |
renderer=tcod.RENDERER_SDL2, | |
vsync=True, | |
) as console: | |
pad = np.zeros((HEIGHT * 2, WIDTH * 2, 3), np.uint8) | |
dots = [Dot() for _ in range(100)] | |
while True: | |
pad[...] //= 2 | |
for dot in dots: | |
dot.draw(pad) | |
dot.step() | |
console.draw_semigraphics(pad) | |
tcod.console_flush() | |
for event in tcod.event.get(): | |
if event.type == "QUIT": | |
raise SystemExit() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment