Skip to content

Commit

Permalink
feat: optimizations, animations
Browse files Browse the repository at this point in the history
  • Loading branch information
ShashkovS committed Aug 15, 2020
1 parent 78bc216 commit 2c8e903
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 59 deletions.
18 changes: 16 additions & 2 deletions drawzero/__init__.py
@@ -1,6 +1,20 @@
"""Draw Zero, a zero-boilerplate graphing library for education.
"""
Draw Zero, a zero-boilerplate graphing library for education.
__version__ = '0.1.4'
Functions:
line(color='red', start=(100, 100), end=(200, 200))
circle(color='red', pos=(100, 100), radius=10)
filled_circle(color='red', pos=(100, 100), radius=10)
rect(color='red', pos=(100, 100), width=500, height=200)
filled_rect(color='red', pos=(100, 100), width=500, height=200)
polygon(color='red', *points)
filled_polygon(color='red', *points)
text(color='red', text='', pos=(100, 100), fontsize=24)
clear()
fill(color='red')
blit(image, pos)
"""

__version__ = '0.1.10'

from .drawzero import *
37 changes: 16 additions & 21 deletions drawzero/drawzero.py
@@ -1,5 +1,9 @@
from . import renderer
import time
import os

if os.environ.get('EJUDGE_MODE', False):
from . import renderer_ejudge as renderer
else:
from . import renderer

c_antiquewhite = (250, 235, 215)
c_aliceblue = (240, 248, 255)
Expand Down Expand Up @@ -148,6 +152,8 @@
THECOLORS = {obj[2:]: globals()[obj] for obj in locals() if obj.startswith('c_')}

_ = lambda x: x # That is for gettext localisation


# _SECRET_PRINT = ''


Expand Down Expand Up @@ -230,39 +236,39 @@ def _make_points_list(points):
def line(color='red', start=(100, 100), end=(200, 200), *args):
"""Draw a line from start to end."""
coords = _make_flat([start, end, args])
parms = _make_pos(coords[:2]), _make_pos(coords[2:4]), _make_color(color)
parms = _make_color(color), _make_pos(coords[:2]), _make_pos(coords[2:4])
# print(_SECRET_PRINT, 'line', parms)
renderer.draw_line(*parms)


def circle(color='red', pos=(100, 100), radius=10, *args):
"""Draw a circle."""
coords = _make_flat([pos, radius, args])
parms = _make_pos(coords[:2]), _make_int(*coords[2:3]), _make_color(color)
parms = _make_color(color), _make_pos(coords[:2]), _make_int(*coords[2:3])
# print(_SECRET_PRINT, 'circle', parms)
renderer.draw_circle(*parms)


def filled_circle(color='red', pos=(100, 100), radius=10, *args):
"""Draw a filled circle."""
coords = _make_flat([pos, radius, args])
parms = _make_pos(coords[:2]), _make_int(*coords[2:3]), _make_color(color)
parms = _make_color(color), _make_pos(coords[:2]), _make_int(*coords[2:3])
# print(_SECRET_PRINT, 'filled_circle', parms)
renderer.draw_filled_circle(*parms)


def rect(color='red', pos=(100, 100), width=500, height=200, *args):
"""Draw a rectangle."""
coords = _make_flat([pos, width, height, args])
parms = _make_rect(coords[:4]), _make_color(color)
parms = _make_color(color), _make_rect(coords[:4])
# print(_SECRET_PRINT, 'rect', parms)
renderer.draw_rect(*parms)


def filled_rect(color='red', pos=(100, 100), width=500, height=200, *args):
"""Draw a filled rectangle."""
coords = _make_flat([pos, width, height, args])
parms = _make_rect(coords[:4]), _make_color(color)
parms = _make_color(color), _make_rect(coords[:4])
# print(_SECRET_PRINT, 'filled_rect', parms)
renderer.draw_filled_rect(*parms)

Expand All @@ -283,7 +289,7 @@ def filled_polygon(color='red', *points):

def text(color='red', text='', pos=(100, 100), fontsize=24, *args, **kwargs):
"""Draw text to the screen."""
parms = text, _make_pos(pos), _make_int(fontsize), _make_color(color)
parms = _make_color(color), text, _make_pos(pos), _make_int(fontsize)
# print(_SECRET_PRINT, 'text', parms)
renderer.draw_text(*parms)

Expand Down Expand Up @@ -327,16 +333,5 @@ class Obj:
screen.draw.polygon = polygon
screen.draw.filled_polygon = filled_polygon
screen.draw.text = text
sleep = time.sleep

FPS = 1 / 60


def tick(reps=1, *, _prev=[0]):
"""Выждать такое время, чтобы частота обновления кадров была 60 FPS"""
for _ in range(reps):
cur = time.time()
dif = _prev[0] + FPS - cur
_prev[0] = cur
if dif > 0:
time.sleep(dif)
tick = renderer.draw_tick
sleep = renderer.draw_sleep
103 changes: 67 additions & 36 deletions drawzero/renderer.py
Expand Up @@ -21,81 +21,100 @@
sys.exit(0)


def _create_surface():
global _surface
if not _surface:
_surface = pygame.display.set_mode((surface_size, surface_size), pygame.locals.RESIZABLE)
_surface.fill((0, 0, 0))
pygame.display.set_caption('Draw Zero')


def draw_resize(width: int, height: int):
global _surface
_surface = pygame.display.set_mode([width, height])
pygame.display.update()
# pygame.display.update()


def draw_line(start: Pt, end: Pt, color: Clr):
def draw_line(color: Clr, start: Pt, end: Pt):
"""Draw a line from start to end."""
_create_surface()
pygame.draw.line(_surface, color, start, end, _dft_wid)
pygame.display.update()
# pygame.display.update()


def draw_circle(pos: Pt, radius: int, color: Clr):
def draw_circle(color: Clr, pos: Pt, radius: int):
"""Draw a circle."""
_create_surface()
pygame.draw.circle(_surface, color, pos, radius, _dft_wid)
pygame.display.update()
# pygame.display.update()


def draw_filled_circle(pos: Pt, radius: int, color: Clr):
def draw_filled_circle(color: Clr, pos: Pt, radius: int):
"""Draw a filled circle."""
_create_surface()
pygame.draw.circle(_surface, color, pos, radius, 0)
pygame.display.update()
# pygame.display.update()


def draw_rect(rect: Rect, color: Clr):
def draw_rect(color: Clr, rect: Rect):
"""Draw a rectangle."""
_create_surface()
pygame.draw.rect(_surface, color, pygame.rect.Rect(rect), _dft_wid)
pygame.display.update()
# pygame.display.update()


def draw_filled_rect(rect: Rect, color: Clr):
def draw_filled_rect(color: Clr, rect: Rect):
"""Draw a filled rectangle."""
_create_surface()
pygame.draw.rect(_surface, color, rect, 0)
pygame.display.update()
# pygame.display.update()


def draw_polygon(color: Clr, points: List[Pt]):
"""Draw a polygon."""
_create_surface()
pygame.draw.polygon(_surface, color, points, _dft_wid)
pygame.display.update()
# pygame.display.update()


def draw_filled_polygon(color: Clr, points: List[Pt]):
"""Draw a filled polygon."""
_create_surface()
pygame.draw.polygon(_surface, color, points, 0)
pygame.display.update()
# pygame.display.update()


def draw_text(text: str, pos: Pt, fontsize: int, color: Clr):
def draw_text(color: Clr, text: str, pos: Pt, fontsize: int):
"""Draw text."""
_create_surface()
use_font = _fonts.get(fontsize, pygame.font.Font(None, fontsize))
temp_surf = use_font.render(text, True, color)
_surface.blit(temp_surf, pos)
pygame.display.update()
# pygame.display.update()


def draw_fill(color: Clr):
"""Fill the screen with a solid color."""
_create_surface()
_surface.fill(color) # Заливаем всё чёрным
pygame.display.update()
# pygame.display.update()


def draw_clear(color: Clr = (0, 0, 0)):
"""Fill the screen with a solid color."""
_create_surface()
_surface.fill(color) # Заливаем всё чёрным
pygame.display.update()
# pygame.display.update()


def draw_blit(image: str, pos: Pt):
"""Draw the image to the screen at the given position."""
_create_surface()
EXTNS = ['png', 'gif', 'jpg', 'jpeg', 'bmp']
TYPE = 'image'
path = image
_surface.blit(pygame.image.load(path).convert_alpha(), pos)
pygame.display.update()
# pygame.display.update()


def _resize(nw: int, nh: int):
Expand All @@ -104,41 +123,55 @@ def _resize(nw: int, nh: int):
scaled = pygame.transform.smoothscale(_surface, (surface_size, surface_size))
_surface = pygame.display.set_mode((surface_size, surface_size), pygame.locals.RESIZABLE)
_surface.blit(scaled, (0, 0))
pygame.display.update()
# pygame.display.update()


def draw_tick():
_fps.tick(60)
def _display_update():
try:
events = pygame.event.get()
pygame.display.update()
except pygame.error:
pygame.quit()
sys.exit()
for event in events:
if event.type == pygame.QUIT:


def draw_tick(r=1, *, display_update=True):
_create_surface()
if display_update:
_display_update()
for __ in range(r):
_fps.tick(30)
try:
events = pygame.event.get()
except pygame.error:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE:
_resize(event.w, event.h)
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE:
_resize(event.w, event.h)


def draw_sleep(t: Union[int, float]):
ticks = int(t * 60 + 0.5)
for __ in range(ticks):
draw_tick()
_create_surface()
ticks = int(t * 30 + 0.5)
draw_tick(ticks)


def draw_set_line_width(w):
_create_surface()
global _dft_wid
_dft_wid = w


def _draw_go():
_display_update()
while True:
draw_tick()
draw_tick(display_update=False)


def _init_surface():
def _init():
if os.name == 'nt':
# need to get screen size with scale factor for HDPI
ctypes.windll.user32.SetProcessDPIAware()
Expand All @@ -148,12 +181,10 @@ def _init_surface():
surface_size = 4 * min(w, h) // 5
# set window position
os.environ['SDL_VIDEO_WINDOW_POS'] = "{},{}".format((w - surface_size) // 2, (h - surface_size) // 2)
_surface = pygame.display.set_mode((surface_size, surface_size), pygame.locals.RESIZABLE)
_surface.fill((0, 0, 0))
pygame.display.set_caption('Draw Zero')
return surface_size, _surface
return surface_size


surface_size, _surface = _init_surface()
_surface = None
surface_size = _init()

atexit.register(_draw_go)
73 changes: 73 additions & 0 deletions drawzero/renderer_ejudge.py
@@ -0,0 +1,73 @@
def jsonize(parms, sep=','):
if type(parms) == int or type(parms) == float:
return str(parms)
elif type(parms) == str:
return '"' + parms.replace('"', '\\"') + '"'
elif type(parms) == list or type(parms) == tuple:
return '[' + sep.join(map(jsonize, parms)) + ']'
else:
raise ValueError('Тип не поддерживается')


def draw_resize(*parms):
print('resize', format(jsonize(parms, sep=', ')))


def draw_line(*parms):
print('line', format(jsonize(parms, sep=', ')))


def draw_circle(*parms):
print('circle', format(jsonize(parms, sep=', ')))


def draw_filled_circle(*parms):
print('filled_circle', format(jsonize(parms, sep=', ')))


def draw_rect(*parms):
print('rect', format(jsonize(parms, sep=', ')))


def draw_filled_rect(*parms):
print('filled_rect', format(jsonize(parms, sep=', ')))


def draw_polygon(*parms):
print('polygon', format(jsonize(parms, sep=', ')))


def draw_filled_polygon(*parms):
print('filled_polygon', format(jsonize(parms, sep=', ')))


def draw_text(*parms):
print('text', format(jsonize(parms, sep=', ')))


def draw_fill(*parms):
print('fill', format(jsonize(parms, sep=', ')))


def draw_clear(*parms):
print('clear', format(jsonize(parms, sep=', ')))


def draw_blit(*parms):
print('blit', format(jsonize(parms, sep=', ')))


def draw_tick(r=1):
print('tick({})'.format(r))


def draw_sleep(t=1):
print('sleep({})'.format(t))


def draw_set_line_width(w):
print('set_line_width({})'.format(w))
pass


surface_size = 1000

0 comments on commit 2c8e903

Please sign in to comment.