Example #1
0
    def __init__(self, overlay, **kwargs):
        super().__init__(**kwargs)
        # creating an interface
        self.controller = overlay
        self.size_hint = (.8, .8)
        self.orientation = 'vertical'
        # starting the gameloop
        self.event = Clock.schedule_interval(self.mainloop, 0)
        # create main canvas
        self.GAME = Widget()
        self.GAME.canvas = Canvas()
        self.add_widget(self.GAME)
        # game classes
        self.player = Player()
        self.sprites = Sprites()
        self.drawing = Drawing(self.GAME.canvas, None)

        # draw borders
        with self.canvas.after:
            Color(.05, .05, .05)
            Rectangle(pos=(0, 0), size=(NULLX, REAL_SCREEN_Y))
            Color(.01, .01, .01)
            Rectangle(pos=(NULLX, REAL_SCREEN_Y - NULLY),
                      size=(REAL_SCREEN_X - NULLX, NULLY))
            Color(.01, .01, .01)
            Rectangle(pos=(NULLX, 0), size=(REAL_SCREEN_X - NULLX, NULLY))
            Color(.05, .05, .05)
            Rectangle(pos=(REAL_SCREEN_X - NULLX, 0),
                      size=(REAL_SCREEN_X, REAL_SCREEN_Y))
Example #2
0
def main(x=HALF_WIDTH // 4, y=HALF_HEIGHT - 50, heart=100, eat=100, energy=100, money=0, *inventory):
    player = Player(sprites, sc, x, y, heart, eat, energy, inventory, money)
    drawing = Drawing(sc, sc_map)
    pygame.mouse.set_visible(False)
    pygame.mixer.music.load('sound\\music\\Free Zen Spirit — Zen Spirit Music.mp3')
    pygame.mixer.music.play()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
        player.movement()
        sc.fill(BLACK)

        drawing.background(player.angle)
        walls = ray_casting_walls(player, drawing.textures)
        drawing.world(walls + [obj.object_locate(player) for obj in sprites.list_of_objects])
        drawing.fps(clock)
        pygame.draw.rect(sc, BLACK, (WIDTH - 400, 0, 700, HEIGHT))
        pygame.draw.rect(sc, BLACK, (0, 0, WIDTH, 30))
        pygame.draw.rect(sc, BLACK, (0, HEIGHT - 50, WIDTH, 100))
        pygame.draw.rect(sc, WHITE, (WIDTH - 400, 0, 700, HEIGHT - 300), 3)
        pygame.draw.rect(sc, WHITE, (WIDTH - 400, HEIGHT - 300, 700, 300), 3)
        player.draw_hp()

        pygame.display.flip()
        clock.tick(FPS)
        '''
Example #3
0
def ParseDrawingsFile(fileName):
    """
    This function reads the input file and returns a list of drawings

    """
    drawings = []
    f = open(fileName)
    for line in f:
        lsplit = line.split()
        drawings.append(Drawing(datetime.strptime(lsplit[0], "%m/%d/%Y"), lsplit[1:6], lsplit[6]))
    f.close()
    return drawings
Example #4
0
    def parse_text_objects(self):
        """
        TODO:
        Returns:

        """
        text_objects_dict = self.parsed_eve_xml['lab'].get('objects')
        if text_objects_dict is not None:
            for text_object_dict in text_objects_dict[0]['textobjects'][
                    'textobject']:
                eve_html = base64.b64decode(text_object_dict['data'])
                self.text_objects.append(
                    Drawing(eve_html=eve_html, topology=self))
Example #5
0
def Main():
    Read_Data()
    translatePoints()
    setPrincipalSign()
    DecideConvexConcavePoints()
    DecidePrincipalsPoints()
    PrintConvexesConcaves()
    PrintPrincipalsNotPrincipals()

    # A ramas partea grafica
    map_points()
    drawing = Drawing(drawing_points)
    drawing.draw()
Example #6
0
 def Pick(self, pastDrawings):
     """Make drawings by picking numbers randomly.
     :param pastDrawings:    Previous drawings that can be used to base picks on
     :type pastDrawings:     list of Drawings
     :return:                list of Drawings created by the picker"""
     randRed = None
     self._picks = []
     for _ in range(self._picksPerDrawing):
         reds = random.sample(range(MAX_WHITE + 1), 5)
         if self._altReds or randRed is None:
             randRed = random.randint(0, MAX_RED)
         draw = Drawing(None, reds, randRed)
         self._picks.append(draw)
     return self._picks
Example #7
0
    def import_dxf(self):
        """Import the DXF file and return structure containing all entities."""
        self.init_import()

        with open(self.filename) as fin:
            lines = 0
            for code, data in self.dxf_entry(fin):
                function = self.state_switcher.get(
                    self.state, lambda self, code, data: "nothing")
                function(self, code, data)
                lines += 1
        print(lines)
        print(self.statistic)
        drawing = Drawing(self.entities, self.statistic, lines)
        return drawing
Example #8
0
    def __init__(self):
        self.programm = None

        self.drawing = Drawing()
        self.rainbowEffect = RainbowEffect(self.drawing, self.nextMode)
        self.runningLightEffect = RunningLightEfect(self.drawing,
                                                    self.nextMode)
        self.waitEffect = WaitEffect(self.drawing, self.nextMode)
        self.appearEffect = AppearEffect(self.drawing, self.nextMode)
        self.cycleEffect = CycleEffect(self.drawing, self.nextMode)
        self.pendulumEffect = PendulumEffect(self.drawing, self.nextMode)
        self.waveEffect = WaveEffect(self.drawing, self.nextMode)
        self.clockEffect = ClockEffect(self.drawing, self.nextMode)
        self.debugEffect = DebugEffect(self.drawing, self.nextMode)

        self.mode = 0
        self.showSingleEffect = False
Example #9
0
def main_cam(gesture_lock):
    cap = cv2.VideoCapture(0)
    address = "http://192.168.1.193:8080/video"
    cap.open(address)

    fps = FPS().start()
    fps_count = 0.0

    drawing = Drawing()

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            print('Video file finished.')
            break
        frame = cv2.flip(frame, 1)
        gesture, action = gesture_lock.get_gesture()
        text = action + " (" + gesture + ")"
        cv2.putText(frame,
                    text=text,
                    org=(30, 100),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=3,
                    color=(0, 255, 20),
                    thickness=5)
        frame = drawing.process_frame(frame, action)

        fps.update()
        if fps._numFrames == 25:
            fps.stop()
            fps_count = fps.fps()
            fps = FPS().start()
        cv2.putText(frame,
                    text=str(round(fps_count, 1)),
                    org=(1750, 50),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=2,
                    color=(0, 255, 20),
                    thickness=3)

        cv2.imshow('Cam', frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cap.release()
    cv2.destroyAllWindows()
Example #10
0
 def import_drawing(self):
     """Import the file and return structure containing all entities."""
     try:
         # read and parse all lines
         with open(self.filename) as fin:
             lines = 0
             for line in fin:
                 self.parse_line(line)
                 lines += 1
         drawing = Drawing(self.entities, self.statistic, lines)
         drawing.rooms = self.rooms
         drawing.drawing_id = self.drawing_id
         # TODO this needs to be improved for deleted rooms
         drawing.room_counter = len(self.rooms) + 1
         return drawing
     except Exception as e:
         print(e)
         return None
Example #11
0
def ParseJackpotFile(fileName):

    jackpots = []
    book = xlrd.open_workbook(fileName)
    jSheet = book.sheet_by_index(0)
    for n in range(jSheet.nrows):
        r = jSheet.row(n)
        #print(r)
        #print(r[0].value)
        try:
            drawingDate = xlrd.xldate.xldate_as_datetime(r[0].value, book.datemode)
            amount = r[2].value
            winnersCol = r[3].value
            winners = re.match("\d+", winnersCol)
            if winners is not None:
                jackpots.append((Drawing(drawingDate, jackpot=amount), winners.group(0)))
        except TypeError:
            pass
    return jackpots
Example #12
0
    def Pick(self, pastDrawings):
        """Make drawings based on the least recent numbers.
        :param pastDrawings:    Previous drawings that can be used to base picks on
        :type pastDrawings:     list of Drawings
        :return:                list of Drawings created by the picker"""

        self._picks = []
        lrReds = LeastRecentReds(pastDrawings)
        lrWhites = LeastRecentWhites(pastDrawings)

        # Pick white balls using permutations of the least recent balls
        permIter = itertools.permutations(lrWhites, r=NUM_WHITES)
        for i in range(self._picksPerDrawing):
            redPick = lrReds[0] if not self._altReds else random.choice(
                lrReds[:NUM_WHITES])
            self._picks.append(
                Drawing(None, numbers=next(permIter), powerball=redPick))

        return self._picks
Example #13
0
def generate_xml(d=1, img_directory="static/images/uploads", img_name="test.jpg", out_file="result.xml",  out_dir="outputs", x_offset=0, y_offset=0):
    im = Image.open(os.path.join(img_directory, img_name))
    pix = im.load()
    first_y, last_y, curr_x, lines, prev_color = 0, 0, 0, [], pix[0, 0]
    thickness = calculate_thickness(d)
    for x in range(0, im.size[0], d):
        for y in range(0, im.size[1], d):
            color = pix[x, y]
            if curr_x == x and color == prev_color:
                last_y = y
            else:
                if first_y == last_y:
                    lines.append(
                        Line(
                            Point(x_offset + x, y_offset + first_y),
                            Point(x_offset + x, y_offset + last_y + 1),
                            Color(prev_color),
                            thickness,
                        )
                    )
                else:
                    lines.append(
                        Line(
                            Point(x_offset + x, y_offset + first_y),
                            Point(x_offset + x, y_offset + last_y),
                            Color(prev_color),
                            thickness,
                        )
                    )
                prev_color = color
                first_y = y
                last_y = y
                curr_x = x
    drawing = Drawing(lines)

    if len(str(drawing)) < get_maximum_size():
        print("Reached an accuracy of: " + str(d))
        output_file = open(os.path.join(out_dir, out_file), "w")
        output_file.write(str(drawing))
        return str(drawing)
    else:
        return generate_xml(d=d + 1, img_directory=img_directory, img_name=img_name, out_dir=out_dir, out_file=out_file, x_offset=x_offset, y_offset=y_offset)
Example #14
0
    def serve_starting_page(s):
        file = s.path.replace('/start.html?f=', '')
        # Basic protection against evil fake file locations
        if ('http://' in file) or ('..' in file) or ('/' in file):
            s.serve_error_page(403)
            return

        file = './uploads/' + file

        # Todo: error handling here - what if the file isn't found?
        d = Drawing(filename=file)
        instructions = d.instructions()

        s.serve_headers(status=200, content_type='text/html')
        s.wfile.write(bytes(start_page, encoding='ISO-8859-1'))

        com = Communicator()
        for i in instructions:
            print("Sending instruction to drawbot: " + i)
            com.sendcommand(i)
        com.close()
 def read_data(self, path):
     bigger_sample_size = int(self.nb_lines * 1.2)
     if self.nb_lines is not None:
         lines = bigger_sample_size * [None]
         with open(path) as f:
             for i in range(bigger_sample_size):
                 line = f.readline()
                 if line:
                     lines[i] = line
                 else:
                     break
         data = ndjson.loads("".join(lines))
     else:
         with open(path) as f:
             data = ndjson.load(f)
     
     res = [Drawing(draw,
                     do_link_strokes=self.do_link_strokes,
                     do_rescale=self.do_rescale,
                     link_steps=self.link_steps,
                     link_timestep=self.link_timestep) for draw in data]
     return [drawing for drawing in res if drawing.recognized][:self.nb_lines]
Example #16
0
    def _draw(self, svg):
        self.speak('Executing draw.')

        landscape = (11.0 * 96, 8.5 * 96)
        portrait = (landscape[1], landscape[0])

        if type(svg) == str:
            svg = os.path.join(self.root, 'svg', svg).replace('\\', '/')

        drawing = Drawing(svg, portrait, center=True, resize=True, dx=20)

        angles, dts = self.agility.draw(drawing, self.params['speed'], self.params['offset'],
                                        self.params['depth'], self.params['lift'])

        eta = dts.sum() / 1000 * 1.1
        self.speak('Estimated completion in {:d} seconds.'.format(int(round(eta))))

        self.event.clear()
        completed = self.agility.execute(angles, dts, event=self.event)

        if not completed:
            self.agility.zero()
Example #17
0
import math
import pygame

from settings import *
from player import Player
from map import world_map
from ray_casting import ray_casting
from drawing import Drawing

pygame.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))
sc_map = pygame.Surface((WIDTH // MAP_SCALE, HEIGHT // MAP_SCALE))
clock = pygame.time.Clock()
player = Player()
drawing = Drawing(screen, sc_map)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    player.movement()
    screen.fill(BlACK)

    drawing.background()
    drawing.world(player_pos, player_angle)
    drawing.fps(clock)
    drawing.mini_map(player)

    pygame.display.flip()
Example #18
0
import pygame
from settings import *
from player import Player
import math
from map import *
from ray_casting import *
from drawing import Drawing

pygame.init()
sc = pygame.display.set_mode((WIDTH, HEIGHT))
sc_map = pygame.Surface((WIDTH //MAP_SCALE, HEIGHT//MAP_SCALE))
clock = pygame.time.Clock()
player = Player()
drawing = Drawing(sc, sc_map)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    player.movement()
    sc.fill(BLACK)

    drawing.background()
    drawing.world(player.pos, player.angle)
    drawing.fps(clock)
    drawing.mini_map(player)

    pygame.display.flip()
    clock.tick()
Example #19
0
from player import Player
from sprite_objects import *
from ray_casting import ray_casting_walls
from drawing import Drawing
from interaction import Interaction

pygame.init()
sc = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
clock = pygame.time.Clock()

sc_map = pygame.Surface(MAP_RES)
sprites = Sprites()
player = Player(sprites)
drawing = Drawing(sc, sc_map, player, clock)
interaction = Interaction(player, sprites, drawing)

drawing.menu()
pygame.mouse.set_visible(False)

while True:

    player.movement()
    drawing.background()
    walls, wall_shot = ray_casting_walls(player, drawing.textures)
    drawing.world(
        walls + [obj.object_locate(player) for obj in sprites.list_of_objects])
    drawing.mini_map()
    drawing.player_weapon([wall_shot, sprites.sprite_shot])
    interaction.interaction_objects()
    interaction.npc_action()
    interaction.clear_world()
Example #20
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import math
import pygame
from drawing import Drawing
from map import world_map
from player import Player
from ray_casting import ray_casting
from settings import *

pygame.init()
game = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
player = Player()
drawing = Drawing(game)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    player.movement()
    game.fill(BLACK)

    drawing.background()
    drawing.world(player.pos, player.angle)
    drawing.fps(clock)

    pygame.display.flip()
    clock.tick(FPS)
Example #21
0
        for events in pygame.event.get():
            if events.type == pygame.QUIT:
                exit(-1)
            if events.type == pygame.USEREVENT:
                if events.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    if events.ui_element == start:
                        run = False
            manager.process_events(events)
        manager.update(time_delta)
        manager.draw_ui(screen)
        screen.blit(text1, (WIDTH // 2 - 90, 100))
        pygame.display.flip()


pygame.init()
player = Player()
drawing = Drawing(screen)

running = True
main_menu()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    player.movement()
    drawing.background()
    drawing.world(player.pos, player.angle)
    drawing.fps(clock)

    pygame.display.flip()
    clock.tick()
def GameMain(sc, playername):
    global enemy_healthBar
    #global enemy
    print("i have started the game")

    #If the player is in battle
    playerIsBattling = False

    #If the player clicks their inventory while in battle this should be True
    battleInvClicked = False
    exited = 0
    sc = pygame.display.set_mode((display_width, display_height))
    sc_map = pygame.Surface(MINIMAP_RES)

    clock = pygame.time.Clock()
    sprites = Sprites()

    #Initialize Player, Inventory, Equipment, Battle UI
    player = Player(playername)
    inventory = invClassHelpers.Inventory(player.startingItems)
    equipment = equipClassHelpers.Equipment()
    battleUI = battle_UIClassHelpers.BattleUI(player, inventory)
    heldItem = None
    # config.text1.append(player.pos)
    drawing = Drawing(sc, sc_map, None)
    second_screen = pygame.Surface((400, 300))
    second_screen.fill(black)
    healthBar = health.Bar(config.white, config.CHAR_DETAIL_FONT_LARGE,
                           (1285, 500), sc)

    #129 Enemy HP Bar, set to a new bar when encountering an enemy
    enemy = None

    while True:
        mouseX, mouseY = pygame.mouse.get_pos()
        sc.fill(black)
        player.movement()
        walls = ray_casting(player, drawing.textures)
        drawing.background(player.angle)
        drawing.world(walls + [
            obj.object_locate(player, healthBar)
            for obj in sprites.list_of_objects
        ])
        sc.blit(second_screen, (0, 0))
        # second_screen.blit(second_screen, (0, config.scroll_y))
        drawing.mini_map(player)
        drawing.ui_elements(player, sc)
        drawing.activities_panel(second_screen)

        if player.won and not playerIsBattling:
            encounter.boss_flag = True
            config.boss_initiate = True
            enemy = encounter.enemy_trigger(sc)
            encounter.in_battle = True
            playerIsBattling = True
            if enemy_healthBar == 0:
                enemy_healthBar = health.Bar(config.white,
                                             config.CHAR_DETAIL_FONT_LARGE,
                                             (100, 650), sc)

        if player.won is True and encounter.boss_defeated:
            transitions.win_screen(sc, player)
        #Player Health Bar & Enemy Health Bar
        healthBar.updateBar()
        if (playerIsBattling):
            enemy_healthBar.updateBar()

        equipment.createEquip()
        activities.iterate_over_input(second_screen, 20)
        if encounter.in_battle and not encounter.enemy_selected:
            enemy = encounter.enemy_trigger(sc)
            print("chose enemy in game")
            if enemy is not None:
                print("In game chose " + enemy.type)
            playerIsBattling = True
            if enemy_healthBar == 0:
                enemy_healthBar = health.Bar(config.white,
                                             config.CHAR_DETAIL_FONT_LARGE,
                                             (100, 650), sc)

        if encounter.in_battle and encounter.enemy_selected and enemy is not None:
            encounter.enemy_blit(sc, enemy)

        if (battleInvClicked):  #When the Open Inventory button is clicked
            inventory.createInventory()
            Button.check_Hover(inventory.back, sc)
            drawing.blitHeldItem(heldItem, mouseX, mouseY)
            drawing.blitMenuInfoBoxes(inventory, equipment)

        else:  #The player is in battle moves menu, not inventory
            battleUI.createBattleUI()

            #the hover check is what's blitting the actions to the screen each time also
            #battleUI.actions[0] to [3] is the player's moves. [4] is "Open Inventory"
            for button in battleUI.actions:
                Button.check_Hover(button, sc)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            #For if the player is in the Inventory and click a button
            elif event.type == pygame.MOUSEBUTTONDOWN and (battleInvClicked):
                #If they clicked "Back" in the Inventory, then go back and break out
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and inventory.back.rect.collidepoint(
                        pygame.mouse.get_pos()):
                    battleInvClicked = False
                    break
                #Otherwise blit everything needed!
                heldItem, healthBar, player = drawing.inventoryEquipmentUI(
                    inventory, equipment, sc, event.type, event.button, mouseX,
                    mouseY, heldItem, healthBar, player)
                drawing.blitMenuInfoBoxes(inventory, equipment)

                if event.button == 4:
                    config.scroll_y = min(
                        config.scroll_y + 20, 0
                    )  #what happens when you scroll is that the activities panel goes
                    #black and then the text are repeated
                    #so you should use the second_screen recursively
                    print('up')
                if event.button == 5:
                    config.scroll_y = max(config.scroll_y - 20, -300)
                    print('down')
                    print(config.scroll_y)

            #129 BATTLE
            #If they left-click
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                if battleUI.actions[4].rect.collidepoint(
                        pygame.mouse.get_pos()):
                    battleInvClicked = True

                elif playerIsBattling:
                    if battleUI.actions[0].rect.collidepoint(
                            pygame.mouse.get_pos()):
                        enemy_healthBar.subtractHealth(player.attack)
                    elif battleUI.actions[1].rect.collidepoint(
                            pygame.mouse.get_pos()):
                        enemy_healthBar.subtractHealth(player.attack)
                    elif battleUI.actions[2].rect.collidepoint(
                            pygame.mouse.get_pos()):
                        enemy_healthBar.subtractHealth(player.attack)
                    elif battleUI.actions[3].rect.collidepoint(
                            pygame.mouse.get_pos()):
                        enemy_healthBar.subtractHealth(player.attack)
                    print(str(enemy_healthBar.currenthealth))
                    enemy_healthBar.updateBar()
                    #Mf got KO'ed bro
                    if enemy_healthBar.currenthealth == 0:
                        playerIsBattling = False
                        encounter.enemy_defeated(sc, player.won)
                    #Let the enemy whack the stupid player here
                    else:
                        damageTaken = player.defense - random.randint(
                            int(enemy.damage[0]), int(enemy.damage[1]))
                        #This means player defense is higher than the damage taken!!@#!@#!@# SO SET IT TO 0 SO THE DAMN PLAYER DONT GET WHACKED
                        if (damageTaken > 0): damageTaken = 0
                        healthBar.subtractHealth(
                            abs(damageTaken))  #Enemy does a range of damage
                        if (healthBar.currenthealth == 0):  #UR DEAD BRO
                            # To reset variables
                            encounter.player_death()
                            exited = 1

        if exited == 1:
            # Do different music here too
            gameDisplay_input = pygame.display.set_mode(
                (config.display_width, config.display_height))
            game_over_text = config.SPOOKY_BIG_FONT.render(
                'Game Over', True, config.red)
            gameDisplay_input.blit(
                game_over_text,
                (config.display_width / 3, config.display_height / 3))
            buttons = [
                Button("Return to Character Selection Screen", config.white,
                       pygame.font.Font("assets/fonts/CHILLER.ttf", 50),
                       (4 * config.display_width / 5,
                        4 * config.display_height / 5), gameDisplay_input)
            ]
            if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1
                    and buttons[0].rect.collidepoint(pygame.mouse.get_pos())):
                character_selection(gameDisplay_input)
                # options_menu.options_menu(gameDisplay_input)

            # options_menu.lost(gameDisplay_input)

            # print("You suck")

        pygame.display.flip()
        clock.tick(60)
Example #23
0
    def __init__(self, drawing_size=(300, 300), window_size=(800, 600)):
        self.drawing_size = drawing_size
        self.window_size = window_size

        self.window = pygame.display.set_mode(window_size)
        pygame.display.set_caption('GNU PAINT3R')
        self.drawing = Drawing(window=self.window,
                               rect=(0, 0),
                               size=self.drawing_size,
                               zoom_factor=2)
        self.clock = pygame.time.Clock()

        self.running = False

        self.MODE_BUTTONS = [
            TextButton(self.window, (self.window_size[0] - 50, 75), (75, 75),
                       'Draw'),
            TextButton(self.window, (self.window_size[0] - 50, 150), (75, 75),
                       'Erase'),
            TextButton(self.window, (self.window_size[0] - 50, 225), (75, 75),
                       'Fill'),
            TextButton(self.window, (self.window_size[0] - 50, 300), (75, 75),
                       'Replace'),
            TextButton(self.window, (self.window_size[0] - 50, 375), (75, 75),
                       'Clear')
        ]
        self.MODE_BUTTONS[0].selected = True
        self.mode = 'd'
        self.modes = ['d', 'e', 'f', 'r', 'c']

        self.BRUSHSIZE_BUTTONS = [
            TextButton(self.window, (self.window_size[0] - 50, 425), (25, 25),
                       '1'),
            TextButton(self.window, (self.window_size[0] - 50, 450), (25, 25),
                       '2'),
            TextButton(self.window, (self.window_size[0] - 50, 475), (25, 25),
                       '3'),
            TextButton(self.window, (self.window_size[0] - 50, 500), (25, 25),
                       '4'),
            TextButton(self.window, (self.window_size[0] - 50, 525), (25, 25),
                       '5')
        ]
        self.BRUSHSIZE_BUTTONS[0].selected = True
        self.brushsize = 1

        self.colors = ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0),
                       (255, 255, 255), (0, 0, 0))

        self.COLOR_BUTTONS = [
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 170, 75),
                        size=(50, 50),
                        base_color=(225, 0, 0),
                        light_color=(255, 0, 0)),
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 120, 75),
                        size=(50, 50),
                        base_color=(0, 225, 0),
                        light_color=(0, 255, 0)),
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 120, 125),
                        size=(50, 50),
                        base_color=(0, 0, 225),
                        light_color=(0, 0, 255)),
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 170, 125),
                        size=(50, 50),
                        base_color=(225, 225, 0),
                        light_color=(255, 255, 0)),
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 120, 175),
                        size=(50, 50),
                        base_color=(225, 225, 225),
                        light_color=(255, 255, 255)),
            ColorButton(window=self.window,
                        center=(self.window_size[0] - 170, 175),
                        size=(50, 50),
                        base_color=(10, 10, 10),
                        light_color=(20, 20, 20)),
        ]
        self.COLOR_BUTTONS[0].selected = True
        self.color = self.colors[0]
Example #24
0
class EPaper(object):

    # only update once an hour within these ranges
    # eval - don't try this at home :) i.e. don't expose envs to alians
    DEAD_TIMES = eval(os.environ.get("DEAD_TIMES", "[]"))
    # whether to display two vertical dots to separate hrs and mins
    CLOCK_HOURS_MINS_SEPARATOR = os.environ.get("CLOCK_HRS_MINS_SEPARATOR",
                                                "true") == "true"
    # whether to prefer AQI temperature instead of DarkSky's
    PREFER_AIRLY_LOCAL_TEMP = os.environ.get("PREFER_AIRLY_LOCAL_TEMP",
                                             "false") == "true"
    # warn states painted black instead of white on red canvas?
    WARN_PAINTED_BLACK_ON_RED = os.environ.get("WARN_PAINTED_BLACK_ON_RED",
                                               "false") == "true"

    DEVICE_TYPE = os.environ.get("EPAPER_TYPE", 'waveshare-2.7')

    if DEVICE_TYPE == 'waveshare-2.7':  # TODO refactor to use enums
        # Display resolution for 2.7"
        EPD_WIDTH = 176
        EPD_HEIGHT = 264
        MONO_DISPLAY = False
    elif DEVICE_TYPE == 'waveshare-4.2':
        # Display resolution for 4.2"
        EPD_WIDTH = 400
        EPD_HEIGHT = 300
        MONO_DISPLAY = True
    else:
        raise Exception('Incorrect epaper screen type: ' + DEVICE_TYPE)

    MONO_DISPLAY = os.environ.get(
        "EPAPER_MONO", "true" if MONO_DISPLAY else "false"
    ) == "true"  # one may override but must replace relevant library edpXinX.py, by default lib for 2.7 is tri-color, 4.2 is mono
    FAST_REFRESH = os.environ.get("EPAPER_FAST_REFRESH", "false") == "true"

    drawing = Drawing(
        os.environ.get("DARK_SKY_UNITS", "si"),
        int(os.environ.get("WEATHER_STORM_DISTANCE_WARN", "10")),
        int(os.environ.get("AQI_WARN_LEVEL", "75")),
        int(os.environ.get("FIRST_TIME_WARN_ABOVE_PERCENT", "50")),
        int(os.environ.get("SECONDARY_TIME_WARN_ABOVE_PERCENT", "50")))

    aqi = None
    if os.environ.get("AIRLY_KEY"):
        aqi = Airly(os.environ.get("AIRLY_KEY"), os.environ.get("LAT"),
                    os.environ.get("LON"),
                    int(os.environ.get("AIRLY_TTL", "20")))
    else:
        aqi = Aqicn(os.environ.get("AQICN_KEY"), os.environ.get("LAT"),
                    os.environ.get("LON"), os.environ.get("AQICN_CITY_OR_ID"),
                    int(os.environ.get("AQICN_TTL", "20")))

    weather = None
    if os.environ.get("OPENWEATHER_KEY"):
        weather = OpenWeather(os.environ.get("OPENWEATHER_KEY"),
                              os.environ.get("LAT"), os.environ.get("LON"),
                              os.environ.get("OPENWEATHER_UNITS", "metric"),
                              int(os.environ.get("OPENWEATHER_TTL", "15")))
    elif os.environ.get("WEATHERBIT_IO_KEY"):
        weather = Weatherbit(os.environ.get("WEATHERBIT_IO_KEY"),
                             os.environ.get("LAT"), os.environ.get("LON"),
                             os.environ.get("WEATHERBIT_IO_UNITS", "M"),
                             int(os.environ.get("WEATHERBIT_IO_TTL", "15")))
    else:
        weather = DarkSky(os.environ.get("DARKSKY_KEY"), os.environ.get("LAT"),
                          os.environ.get("LON"),
                          os.environ.get("DARKSKY_UNITS", "si"),
                          int(os.environ.get("DARKSKY_TTL", "15")))

    meteoalarm = None
    if os.environ.get('METEOALARM_COUNTRY') and os.environ.get(
            'METEOALARM_PROVINCE'):
        meteoalarm = Meteoalarm(
            os.environ.get("METEOALARM_COUNTRY").decode('utf-8'),
            os.environ.get("METEOALARM_PROVINCE").decode('utf-8'),
            int(os.environ.get("METEOALARM_TTL", "15")))

    gmaps1 = GMaps(os.environ.get("GOOGLE_MAPS_KEY"), os.environ.get("LAT"),
                   os.environ.get("LON"),
                   os.environ.get("FIRST_TIME_TO_DESTINATION_LAT"),
                   os.environ.get("FIRST_TIME_TO_DESTINATION_LON"),
                   os.environ.get("GOOGLE_MAPS_UNITS", "metric"), "primary",
                   int(os.environ.get("GOOGLE_MAPS_TTL", "10")))
    gmaps2 = GMaps(os.environ.get("GOOGLE_MAPS_KEY"), os.environ.get("LAT"),
                   os.environ.get("LON"),
                   os.environ.get("SECOND_TIME_TO_DESTINATION_LAT"),
                   os.environ.get("SECOND_TIME_TO_DESTINATION_LON"),
                   os.environ.get("GOOGLE_MAPS_UNITS", "metric"), "secondary",
                   int(os.environ.get("GOOGLE_MAPS_TTL", "10")))
    system_info = SystemInfo()

    def __init__(self, debug_mode=False):

        self._debug_mode = debug_mode
        if not debug_mode:
            if self.DEVICE_TYPE == 'waveshare-2.7':
                if self.FAST_REFRESH:
                    logging.info("Using experimental LUT tables!")
                    from epds import epd2in7b_fast_lut
                    self._epd = epd2in7b_fast_lut.EPD()
                else:
                    from epds import epd2in7b
                    self._epd = epd2in7b.EPD()
            elif self.DEVICE_TYPE == 'waveshare-4.2':
                from epds import epd4in2
                self._epd = epd4in2.EPD()

            self._epd.init()

        self._str_time = "XXXX"

    def display(self, black_buf, red_buf, name):
        if self._debug_mode:
            debug_output = "/tmp/epaper-" + (name.strftime("%H-%M-%S") if
                                             type(name) is not str else name)
            logging.info("Debug mode - saving screen output to: " +
                         debug_output + "* bmps")
            black_buf.save(debug_output + "_bw_frame.bmp")
            red_buf.save(debug_output + "_red_frame.bmp")
            return

        if not self.MONO_DISPLAY:
            logging.info("Going to display a new tri-color image...")
            self._epd.display_frame(self._epd.get_frame_buffer(black_buf),
                                    self._epd.get_frame_buffer(red_buf))
        else:
            logging.info("Going to display a new mono-color image...")
            self._epd.display_frame(self._epd.get_frame_buffer(black_buf))

    def display_buffer(self, black_buf, red_buf, dt):

        if self.DEVICE_TYPE == 'waveshare-2.7':
            black_buf = black_buf.transpose(Image.ROTATE_90)
            black_buf = black_buf.resize((self.EPD_WIDTH, self.EPD_HEIGHT),
                                         Image.LANCZOS)

            red_buf = red_buf.transpose(Image.ROTATE_90)
            red_buf = red_buf.resize((self.EPD_WIDTH, self.EPD_HEIGHT),
                                     Image.LANCZOS)

        self.display(black_buf, red_buf, dt)

    def display_shutdown(self):
        black_frame, red_frame = self.drawing.draw_shutdown(self.MONO_DISPLAY)
        self.display_buffer(black_frame, red_frame, 'shutdown')

    def display_aqi_details(self):
        black_frame, red_frame = self.drawing.draw_aqi_details(self.aqi.get())
        self.display_buffer(black_frame, red_frame, 'aqi')

    def display_gmaps_details(self):
        black_frame, red_frame = self.drawing.draw_gmaps_details(
            self.gmaps1.get(), self.gmaps2.get())
        self.display_buffer(black_frame, red_frame, 'gmaps')

    def display_weather_details(self):
        black_frame, red_frame = self.drawing.draw_weather_details(
            self.merge_weather_and_meteo(self.weather, self.meteoalarm))
        self.display_buffer(black_frame, red_frame, 'weather')

    def display_system_details(self):
        black_frame, red_frame = self.drawing.draw_system_details(
            self.system_info.get())
        self.display_buffer(black_frame, red_frame, 'system')

    def cycle_display(self):
        black_frame, red_frame, white_frame = self.drawing.draw_blanks()
        for cycle in range(1, 3):
            for cycle_blacks in range(1, 5):
                self.display_buffer(black_frame, white_frame, '')
            for cycle_whites in range(1, 5):
                self.display_buffer(white_frame, white_frame, '')
            for cycle_reds in range(1, 10):
                self.display_buffer(white_frame, red_frame, '')

    def display_main_screen(self, dt, force=False):
        time_format = "%H%M"
        formatted = dt.strftime(time_format)

        # set blank minutes if time's hour is within dead ranges
        h = formatted[:2]
        for dead_range in self.DEAD_TIMES:
            if int(h) in dead_range:
                formatted = "{}  ".format(h)

        if force or formatted != self._str_time:

            weather_data = self.merge_weather_and_meteo(
                self.weather, self.meteoalarm)
            logging.info("--- weather: " + json.dumps(weather_data))

            aqi_data = self.aqi.get()
            logging.info("--- aqi: " + json.dumps(aqi_data))

            gmaps1_data = self.gmaps1.get()
            logging.info("--- gmaps1: " + json.dumps(gmaps1_data))

            gmaps2_data = self.gmaps2.get()
            logging.info("--- gmaps2: " + json.dumps(gmaps2_data))

            black_frame, red_frame = self.drawing.draw_frame(
                self.MONO_DISPLAY, formatted, self.CLOCK_HOURS_MINS_SEPARATOR,
                weather_data, self.PREFER_AIRLY_LOCAL_TEMP,
                self.WARN_PAINTED_BLACK_ON_RED, aqi_data, gmaps1_data,
                gmaps2_data)
            self.display_buffer(black_frame, red_frame, dt)

            self._str_time = formatted

    def merge_weather_and_meteo(self, weather, meteoalarm):
        w = weather.get()
        result = w
        if meteoalarm:
            m = meteoalarm.get()
            result = w._replace(
                provider="%s & %s" % (w.provider, m.provider)
                if m.alert_title or m.alert_description else w.provider,
                alert_title=w.alert_title if w.alert_title else m.alert_title,
                alert_description=w.alert_description
                if w.alert_description else m.alert_description)
        return result
Example #25
0
from datetime import date
from drawing import Drawing

# Test comparing two picks
theDrawing = Drawing(date.today(), numbers=[1, 2, 3, 4, 5], powerball=1)
print(theDrawing)

#
pick1 = Drawing(None, numbers=[1, 2, 3, 4, 5], powerball=1)
print(theDrawing.MatchingNumbers(pick1))
print(theDrawing.MatchingPowerball(pick1))
print(theDrawing.IsJackpot(pick1))
print(theDrawing.WinAmount(pick1))
Example #26
0
 def drawing(self):
     return Drawing(self.paths)
Example #27
0
 def display(self):
     Drawing(player=self.toDict())
Example #28
0
 def display(self):
     Drawing(dealer=self.toDict())
class EPaper(object):

    # only update once an hour within these ranges
    # eval - don't try this at home :) i.e. don't expose envs to alians
    DEAD_TIMES = eval(os.environ.get("DEAD_TIMES", "[]"))
    # whether to display two vertical dots to separate hrs and mins
    CLOCK_HOURS_MINS_SEPARATOR = os.environ.get("CLOCK_HRS_MINS_SEPARATOR",
                                                "true") == "true"
    # whether to prefer AQI temperature instead of DarkSky's
    PREFER_AIRLY_LOCAL_TEMP = os.environ.get("PREFER_AIRLY_LOCAL_TEMP",
                                             "false") == "true"

    DEVICE_TYPE = os.environ.get("EPAPER_TYPE", 'waveshare-2.7')

    if DEVICE_TYPE == 'waveshare-2.7':  # TODO refactor to use enums
        # Display resolution for 2.7"
        EPD_WIDTH = 176
        EPD_HEIGHT = 264
        MONO_DISPLAY = False
    elif DEVICE_TYPE == 'waveshare-4.2':
        # Display resolution for 4.2"
        EPD_WIDTH = 400
        EPD_HEIGHT = 300
        MONO_DISPLAY = True
    else:
        raise Exception('Incorrect epaper screen type: ' + DEVICE_TYPE)

    MONO_DISPLAY = os.environ.get(
        "EPAPER_MONO", "true" if MONO_DISPLAY else "false"
    ) == "true"  # one may override but must replace relevant library edpXinX.py, by default lib for 2.7 is tri-color, 4.2 is mono
    FAST_REFRESH = os.environ.get("EPAPER_FAST_REFRESH", "false") == "true"

    drawing = Drawing(
        os.environ.get("DARK_SKY_UNITS", "si"),
        int(os.environ.get("WEATHER_STORM_DISTANCE_WARN", "10")),
        int(os.environ.get("AQI_WARN_LEVEL", "75")),
        int(os.environ.get("FIRST_TIME_WARN_ABOVE_PERCENT", "50")),
        int(os.environ.get("SECONDARY_TIME_WARN_ABOVE_PERCENT", "50")))

    airly = Luftdaten(os.environ.get("LAT"), os.environ.get("LON"),
                      int(os.environ.get("AIRLY_TTL", "20")))
    weather = Weather(os.environ.get("DARKSKY_KEY"), os.environ.get("LAT"),
                      os.environ.get("LON"),
                      os.environ.get("DARKSKY_UNITS", "si"),
                      int(os.environ.get("DARKSKY_TTL", "15")))
    system_info = SystemInfo()

    events = ICal(os.environ.get("EVENTS_ICAL_URL"))

    def __init__(self, debug_mode=False):

        self._debug_mode = debug_mode
        if not debug_mode:
            if self.DEVICE_TYPE == 'waveshare-2.7':
                if self.FAST_REFRESH:
                    logging.info("Using experimental LUT tables!")
                    from epds import epd2in7b_fast_lut
                    self._epd = epd2in7b_fast_lut.EPD()
                else:
                    from epds import epd2in7b
                    self._epd = epd2in7b.EPD()
            elif self.DEVICE_TYPE == 'waveshare-4.2':
                from epds import epd4in2
                self._epd = epd4in2.EPD()

            self._epd.init()

        self._str_time = "XXXX"

    def display(self, black_buf, red_buf, name):
        if self._debug_mode:
            debug_output = "test/epaper-" + (name.strftime("%H-%M-%S") if
                                             type(name) is not str else name)
            logging.info("Debug mode - saving screen output to: " +
                         debug_output + "* bmps")
            black_buf.save(debug_output + "_bw_frame.bmp")
            if not self.MONO_DISPLAY:
                red_buf.save(debug_output + "_red_frame.bmp")
            return

        if not self.MONO_DISPLAY:
            logging.info("Going to display a new tri-color image...")
            self._epd.display_frame(self._epd.get_frame_buffer(black_buf),
                                    self._epd.get_frame_buffer(red_buf))
        else:
            logging.info("Going to display a new mono-color image...")
            self._epd.display_frame(self._epd.get_frame_buffer(black_buf))

    def display_buffer(self, black_buf, red_buf, dt):

        if self.DEVICE_TYPE == 'waveshare-2.7' and not self._debug_mode:
            black_buf = black_buf.transpose(Image.ROTATE_90)
            black_buf = black_buf.resize((self.EPD_WIDTH, self.EPD_HEIGHT),
                                         Image.LANCZOS)

            red_buf = red_buf.transpose(Image.ROTATE_90)
            red_buf = red_buf.resize((self.EPD_WIDTH, self.EPD_HEIGHT),
                                     Image.LANCZOS)

        self.display(black_buf, red_buf, dt)

    def display_shutdown(self):
        black_frame, red_frame = self.drawing.draw_shutdown(self.MONO_DISPLAY)
        self.display_buffer(black_frame, red_frame, 'shutdown')

    def display_airly_details(self):
        black_frame, red_frame = self.drawing.draw_airly_details(
            self.airly.get())
        self.display_buffer(black_frame, red_frame, 'airly')

    def display_weather_forecast(self):
        black_frame, red_frame = self.drawing.draw_weather_forecast(
            self.weather.get())
        self.display_buffer(black_frame, red_frame, 'forecast')

    def display_weather_details(self):
        black_frame, red_frame = self.drawing.draw_weather_details(
            self.weather.get())
        self.display_buffer(black_frame, red_frame, 'weather')

    def display_system_details(self):
        black_frame, red_frame = self.drawing.draw_system_details(
            self.system_info.get())
        self.display_buffer(black_frame, red_frame, 'system')

    def display_main_screen(self, dt, force=False):
        time_format = "%H%M"
        formatted = dt.strftime(time_format)

        # set blank minutes if time's hour is within dead ranges
        h = formatted[:2]
        for dead_range in self.DEAD_TIMES:
            if int(h) in dead_range:
                formatted = "{}  ".format(h)

        if force or formatted != self._str_time:

            weather_data = self.weather.get()
            logging.info("--- weather: " + json.dumps(weather_data))

            airly_data = self.airly.get()
            logging.info("--- airly: " + json.dumps(airly_data))

            events_data = self.events.get()

            black_frame, red_frame = self.drawing.draw_frame(
                self.MONO_DISPLAY, events_data,
                self.CLOCK_HOURS_MINS_SEPARATOR, weather_data,
                self.PREFER_AIRLY_LOCAL_TEMP, airly_data)
            self.display_buffer(black_frame, red_frame, dt)

            self._str_time = formatted
Example #30
0
`YouTube <https://www.youtube-nocookie.com/embed/2X3LfF__rnQ?rel=0>`_

"""

#
# Code under the MIT license by Alexander Pruss
#

from drawing import Drawing
from math import pi, sin, cos
import time
import displayprovider
import configuration as conf

fdd = displayprovider.get_display(conf.WIDTH, conf.HEIGHT)
d = Drawing(fdd)
d.penwidth(1)


class Hand:
    def __init__(self, center, scale, length):
        self.center = center
        self.length = length
        self.scale = scale
        self.previousValue = None

    def update(self, value):
        if self.previousValue is not None and self.previousValue is not value:
            self.drawLine(self.previousValue, True)
        self.drawLine(value, False)
        self.previousValue = value