示例#1
0
    def render(self):

        screen_x = int_or_percent(self.entity.screen_x, engine.get().window.size[0])
        screen_y = int_or_percent(self.entity.screen_y, engine.get().window.size[1])

        texture = sdl2hl.Texture(self.renderer, self.pixel_format, sdl2hl.TextureAccess.target, self._screen_width(), self._screen_height())

        self.renderer.render_target = texture

        self.transform_point = self.world_to_camera
        self.transform_angle = self.world_to_camera_angle
        self.transform_width = self.world_to_camera_width
        self.transform_height = self.world_to_camera_height

        for layer in self.layers:
            layer.draw(self)

        self.transform_point = self.hud_to_camera
        self.transform_angle = self.hud_to_camera_angle
        self.transform_width = self.hud_to_camera_length
        self.transform_height = self.hud_to_camera_height

        for e in self.hud_entities:
            e.handle('draw', self)

        self.renderer.render_target = None

        self.renderer.copy(texture,
                           source_rect=None,
                           dest_rect=sdl2hl.Rect(screen_x, screen_y, self._screen_width(), self._screen_height()))
 def handle_draw(self, entity, camera):
     if len(entity.text) > 0:
         font = engine.get().resource_manager.get('font', (entity.font, entity.size))
         surface = font.render_solid(entity.text, entity.colour)
         texture = sdl2hl.Texture.from_surface(engine.get().renderer, surface)
         x,y = camera.screen_percent_point(entity.topleft)
         r = rectangle.Rect(x + texture.w/2, y - texture.h/2, texture.w, texture.h)
         camera.draw_image(r, texture)
    def add(self, entity):
        Component.add(self, entity)

        font = engine.get().resource_manager.get('font', (entity.font, entity.size))
        surface = font.render_solid(entity.text, entity.colour)
        entity.texture = sdl2hl.Texture.from_surface(engine.get().renderer, surface)

        entity.width = entity.texture.w
        entity.height = entity.texture.h
示例#4
0
 def __init__(self, static_data_name, **kwargs):
     self._static_data_name = static_data_name      
     self._handlers = {}
     
     for attribute, value in kwargs.items():
         setattr(self, attribute, value)
         
     if 'components' in self.__dict__ or 'components' in self.static._fields:
         for component in self.components:
             engine.get().component_manager.add(component, self)
             
     if not ('name' in self.__dict__ or 'name' in self.static._fields):
         self.name = str(uuid.uuid4())
示例#5
0
def get():
    req = request.get_json(force=True)
    response = eng.get(req)

    logging.debug(response)

    return jsonify(response)
示例#6
0
    def draw(self, camera):

        entities_to_draw = sorted(engine.get().entity_manager.get_in_area(self.tag, rectangle.from_entity(camera.entity), precise=False),
                                  key=lambda entity: rectangle.from_entity(entity).bottom)

        for entity in entities_to_draw:
            entity.handle('draw', camera)
def LoadEntityData(prefix, key):
    with open(os.path.join(prefix, "entities", key + ".json")) as in_file:
        definition = json.load(in_file)

    if "animations" in definition:
        for animation in definition["animations"].values():
            if "frame_dir" in animation:
                frame_dir = os.path.join(prefix, "images", animation["frame_dir"])
                frames = sorted(os.listdir(frame_dir))
                animation["frames"] = []
                for frame in frames:
                    animation["frames"].append(os.path.join(frame_dir, frame))

    if "includes" in definition:
        flattened = {}
        for include_name in definition["includes"]:
            include = engine.get().resource_manager.get("entity", include_name)
            for field in include._fields:
                flattened[field] = getattr(include, field)
        for key, value in definition.iteritems():
            if key.endswith("+"):
                base_key = key[:-1]
                flattened[base_key] = flattened.get(base_key, tuple()) + tuple(value)
            else:
                flattened[key] = value
        definition = flattened

    return freezejson.freeze_value(definition)
示例#8
0
    def draw(self, camera):
        world = engine.get().box2d_world

        query = DrawQueryCallback(camera)

        rect = rectangle.from_entity(camera.entity).bounding_rect()

        aabb = Box2D.b2AABB(lowerBound=Box2D.b2Vec2(rect.bottom_left),upperBound=Box2D.b2Vec2(rect.top_right))

        world.QueryAABB(query, aabb)
示例#9
0
    def process_events(self):
        self._input_map = engine.get().resource_manager.get('inputmap', 'default')
        processed_events = []

        for e in sdl2hl.events.poll():
            if e.type == sdl2hl.EventType.quit:
                processed_events.append(InputEvent('ENGINE', 'QUIT', 1))

            elif e.type == sdl2hl.EventType.controlleraxismotion:
                event = self._new_event(e.which, e.axis, e.value / 32767.0)
                if event != None:
                    processed_events.append(event)
            elif e.type == sdl2hl.EventType.controllerbuttondown:
                event = self._new_event(e.which, e.button, 1)
                if event != None:
                    processed_events.append(event)
            elif e.type == sdl2hl.EventType.controllerbuttonup:
                event = self._new_event(e.which, e.button, 0)
                if event != None:
                    processed_events.append(event)

            elif e.type == sdl2hl.EventType.keydown:
                event = self._new_event(None, e.keycode, 1)
                if event != None:
                    processed_events.append(event)
            elif e.type == sdl2hl.EventType.keyup:
                event = self._new_event(None, e.keycode, 0)
                if event != None:
                    processed_events.append(event)
                    
            elif e.type == sdl2hl.EventType.mousebuttondown:
                event = self._new_event(None, e.button, 1)
                if event != None:
                    processed_events.append(event)
            elif e.type == sdl2hl.EventType.mousebuttonup:
                event = self._new_event(None, e.button, 0)
                if event != None:
                    processed_events.append(event)
            else:
                pass
        
        return processed_events
def LoadMap(prefix, key):
    with open(os.path.join(prefix, "maps", key + ".csv")) as in_file:
        section = 0
        y = 0
        legend = {}
        entities = []

        for line in in_file:
            if section == 0:
                if line.split(",")[0] == "":
                    section = 1
                else:
                    tile_size = line.split(",")
                    tile_width = int(tile_size[0])
                    tile_height = int(tile_size[1])
            elif section == 1:
                if line.split(",")[0] == "":
                    section = 2
                else:
                    split_line = line.split(",")
                    legend[split_line[0].strip()] = [e.strip() for e in split_line[1:] if e.strip() != ""]
            elif section == 2:
                for x, cell in enumerate(line.split(",")):
                    if cell.strip() != "":
                        for entity in legend[cell.strip()]:
                            entity_data = engine.get().resource_manager.get("entity", entity)
                            entities.append(
                                (
                                    entity,
                                    {
                                        "x": x * tile_width + entity_data.width / 2.0,
                                        "y": y * tile_height + entity_data.height / 2.0,
                                    },
                                )
                            )
                y -= 1
        return entities
示例#11
0
 def screen_percent_point(self, p):
     return (int_or_percent(p[0],  engine.get().window.size[0]), int_or_percent(p[1], engine.get().window.size[1]))
示例#12
0
 def _screen_width(self):
     return int_or_percent(self.entity.screen_width, engine.get().window.size[0])
示例#13
0
 def _screen_height(self):
     return int_or_percent(self.entity.screen_height, engine.get().window.size[1])
 def handle_update(self, entity, dt):
     entity.x += dt * entity.vx
     entity.y += dt * entity.vy
     engine.get().entity_manager.update_position(entity)
示例#15
0
 def static(self):
     return engine.get().resource_manager.get('entity', self._static_data_name)
示例#16
0
def run_game():
    # Define colours for convenience
    BLACK = [0, 0, 0]
    WHITE = [255, 255, 255]
    COLOUR_WHITE = [200, 200, 200]
    COLOUR_BlACK = [50, 50, 50]

    # Manage framerate
    global clock
    clock = pygame.time.Clock()

    # initialize screen
    size = [1280, 800]
    global screen
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('Chess v0.5 ')
    font = pygame.font.SysFont('default', 22)

    # Track allowed and castlable squares, and check
    global allowed_sqs
    global check
    allowed_sqs = []
    check = False

    # Track moves made
    global moves
    moves = []
    global engine_moves
    engine_moves = []
    # Get width and height of window, compute box dimensions
    w, h = pygame.display.get_surface().get_size()
    play_area = min([w, h])
    global box_side
    box_side = play_area / 8

    # Create global live_board variable populate it from ini file
    global live_board
    live_board = set_board('board.ini')

    # Set up sidebar buttons
    global buttons
    buttons = {}
    global initial_time
    initial_time = 25 * 60
    global increment
    increment = 0
    global clock_time
    clock_time = [initial_time, initial_time]
    initialize_sidebar()

    # Set starting turn to white
    global turn_colour
    global counter
    turn_colour = ['w', 'b']
    counter = 0

    # Queening screen check
    global queening
    queening = [False, None]

    # Set up engine
    global AI
    AI = engine.load('ai/stockfish-8-linux/Linux/stockfish_8_x64')
    engine.put(AI, 'uci')
    engine.put(AI, 'uci setoption name Skill Level value 0')
    engine.put(AI, 'ucinewgame')
    garbage = engine.get(AI)
    print 'AI started.'

    global AI_plays
    AI_plays = False

    # Loop until user closes
    global done
    done = False
    #  ------- Main Program Loop ------
    while not done:

        #  --- Main event loop ---
        for event in pygame.event.get():
            m_pos = pygame.mouse.get_pos()
            if event.type == pygame.QUIT:
                quit_game()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If mouse over moves list, handle scrolling
                if (829 < m_pos[0] < (829 + 250)) and (101 < m_pos[1] <
                                                       (101 + 335)):
                    if event.button == 4:
                        scroll_moves_up()
                    elif event.button == 5:
                        scroll_moves_down()
                # If mouse is over board, do chess logic
                if 0 < m_pos[0] < 800:
                    m_sq = pix_to_classic(m_pos)
                    # Right click delesects all board
                    if pygame.mouse.get_pressed() == (0, 0, 1):
                        for piece_ in live_board:
                            deselect(piece_)
                    # Left click
                    elif pygame.mouse.get_pressed() == (1, 0, 0):
                        for piece_ in live_board:
                            if getattr(piece_, 'selected') == True:
                                if m_sq in allowed_sqs:
                                    turn(piece_, m_sq)
                            # If there's a piece on the square we clicked, and that piece is of the right colour
                            # deselect everything, and select that piece.
                            elif getattr(piece_,
                                         'pos') == m_sq and turn_colour[
                                             counter % 2] == getattr(
                                                 piece_, 'colour'):
                                for all_piece in live_board:
                                    deselect(all_piece)
                                select(piece_)
            # Quit on 'q'
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    quit_game()

        #  --- Drawing code ---

        # Display moves to the right of the board

        screen.fill([255, 255, 255])

        if queening[0]:
            # Fill with grey
            pygame.draw.rect(screen, [100, 100, 100], (0, 0, 800, 800))
            # Draw queening options
            textfont = pygame.font.Font('assets/Lato-Bold.ttf', 72)
            draw_text('Choose your piece', textfont, [0, 0, 0], 75, 100)
            available_piecetypes = ['queen', 'knight', 'bishop', 'rook']
            for i in range(0, len(available_piecetypes)):
                try:
                    draw_im_button('assets/'+ available_piecetypes[i] + '_' + getattr(queening[1], 'colour') + '.png'\
                        , 50 + i*200, 200, queen_piece, [queening[1], available_piecetypes[i], live_board])
                except AttributeError:
                    continue

        else:
            # Draw board and pieces
            draw_board(COLOUR_WHITE, COLOUR_BlACK)
            for piece_ in live_board:
                draw_piece(piece_)
            for sq in allowed_sqs:
                highlight(sq)
            check = in_check(turn_colour[counter % 2], live_board)
            if check:
                king = [
                    x for x in live_board
                    if getattr(x, 'colour') == turn_colour[counter % 2]
                    and getattr(x, 'type_') == 'king'
                ]
                highlight(getattr(king[0], 'pos'), [254, 86, 160])

        draw_sidebar()

        pygame.display.flip()

        # Limit fps
        clock.tick(60)

        # Update clock
        if not queening[0] and not checkmate(turn_colour[counter % 2],
                                             live_board):
            frametime = clock.get_time()
            if counter > 0:
                clock_time[counter % 2] -= frametime * 0.001

        if AI_plays:
            turn_engine()

    # Exit gracefully
    pygame.quit()
示例#17
0
 def draw(self, camera):
     for entity in engine.get().entity_manager.get_in_area(self.tag, rectangle.from_entity(camera.entity)):
         entity.handle('draw', camera)
示例#18
0
 def draw(self, camera):
     for entity in engine.get().entity_manager.get_by_tag(self.tag):
         entity.handle('draw', camera)
 def handle_draw(self, entity, camera):
     camera.draw_image(rectangle.from_entity(entity), engine.get().resource_manager.get('image', entity.image))
示例#20
0
 def hud_to_camera_length(self, w):
     return int_or_percent(w, engine.get().window.size[0])
示例#21
0
 def hud_to_camera_height(self, h):
     return int_or_percent(h, engine.get().window.size[1])
def LoadImage(prefix, key):
    texture = sdl2hl.image.load_texture(engine.get().renderer, os.path.join(prefix, "images", key))

    return texture