Exemplo n.º 1
0
    def processInputEvent(self, event: sdl2.SDL_Event):
        # We'll want to return a GameEvent, and these fields
        # are the same regardless of what the rest of the event is
        game_event_dict = {
            "type": "PLAYER",
            "player_id": self.id,
            "pos": self.collider.pos.to_dict()
        }

        if event.type == sdl2.SDL_KEYDOWN or event.type == sdl2.SDL_KEYUP:
            state = ControlsState.state

            vel = Vec2()

            vel.x = state[sdl2.SDLK_d] - state[sdl2.SDLK_a]
            vel.y = state[sdl2.SDLK_s] - state[sdl2.SDLK_w]
            if (vel.length() > 0):
                vel = vel / vel.length()

            vel = vel * self.speed

            game_event_dict["code"] = "CHANGE_VELOCITY"
            game_event_dict["velocity"] = vel.to_dict()

            return GameEvent(game_event_dict)

        if (event.type == sdl2.SDL_MOUSEBUTTONDOWN):
            mouseX, mouseY = ctypes.c_int(0), ctypes.c_int(
                0)  # Create two ctypes values
            # Pass x and y as references (pointers) to SDL_GetMouseState()
            buttonstate = sdl2.mouse.SDL_GetMouseState(ctypes.byref(mouseX),
                                                       ctypes.byref(mouseY))
            x = mouseX.value - graphics.view.game_view.x
            y = mouseY.value - graphics.view.game_view.y
            game_event_dict["code"] = "SHOOT"
            direction_x = x - self.collider.pos.x
            direction_y = y - self.collider.pos.y
            length = math.sqrt(direction_x**2 + direction_y**2)
            direction_x = direction_x / length
            direction_y = direction_y / length
            game_event_dict["direction_x"] = direction_x
            game_event_dict["direction_y"] = direction_y
            #print(game_event_dict)
            return GameEvent(game_event_dict)

        game_event_dict["code"] = "NONE"
        return GameEvent(game_event_dict)
Exemplo n.º 2
0
 def get_update_event(self, room_x, room_y):
     game_event_dict = {
         "type": "STATUS",
         "kind": "ROOM",
         "room_x": room_x,
         "room_y": room_y,
         "room": self.board[room_x][room_y].to_dict()
     }
     return GameEvent(game_event_dict)
Exemplo n.º 3
0
    def onDoor(self, obj1, obj2):
        obj1 = obj1.owner
        obj2 = obj2.owner
        if isinstance(obj1, Door):
            foo = obj1
            obj1 = obj2
            obj2 = foo

        if not isinstance(obj1, Player) or not isinstance(obj2, Door):
            return
        if obj1.id != gameplay.state.my_player_id:
            return
        gameplay.state.players[gameplay.state.my_player_id].setRoom(
            obj2.toX, obj2.toY)
        self.collider.pos = Vec2(500, 300)

        leftX = 64 + self.width / 2
        midX = graphics.view.GAME_WIDTH / 2
        rightX = graphics.view.GAME_WIDTH - 64 - self.width / 2
        topY = 64 + self.height / 2
        midY = graphics.view.WINDOW_SIZE[1] / 2
        botY = graphics.view.WINDOW_SIZE[1] - 64 - self.height / 2

        newXLoc = 300
        newYLoc = 300
        if obj2.dir == 0:
            newXLoc = midX
            newYLoc = botY
        elif obj2.dir == 1:
            newXLoc = leftX
            newYLoc = midY
        elif obj2.dir == 2:
            newXLoc = midX
            newYLoc = topY
        elif obj2.dir == 3:
            newXLoc = rightX
            newYLoc = midY
        self.collider.pos = Vec2(newXLoc, newYLoc)

        for collider in gameplay.state.floor.board[obj2.fromX][
                obj2.fromY].simulation.objects:
            if isinstance(collider.owner, Player):
                gameplay.state.floor.board[obj2.fromX][
                    obj2.fromY].simulation.remove_object(collider)

        game_event_dict = {
            "type": "PLAYER",
            "code": "CHANGE_ROOM",
            "player_id": self.id,
            "pos": self.collider.pos.to_dict(),
            "velocity": self.collider.vel.to_dict(),
            "room_x": self.roomX,
            "room_y": self.roomY
        }

        event = GameEvent(game_event_dict)
        gameplay.state.global_queue.put(event)
Exemplo n.º 4
0
def main():
    gameplay.state.curr_id = 3389
    if len(sys.argv) < 3:
        print("Please provide player file name and player id")
        sys.exit(1)

    gameplay.state.my_player_id = None
    players_str = None
    with open(sys.argv[1], "r") as player_file:
        gameplay.state.my_player_id = int(sys.argv[2])
        players_str = player_file.read()

    player_adds = players_str.split()
    num_players = len(player_adds)

    messaging = MessagingHandler()
    messaging.connect(player_adds, num_players, gameplay.state.my_player_id)

    running = True

    graphics.view.initView()
    gameplay.state.trapDoor = graphics.view.sprite_factory.from_file(
        "./assets/trapdoor.png")
    gameplay.state.floor = Floor()

    if gameplay.state.my_player_id == 0:
        gameplay.state.floor.genFloor(3, 3)
        messaging.broadcast(gameplay.state.floor.serialize().encode("utf-8"))
    else:
        queue = messaging.get_messages()
        while queue.empty():
            sdl2.SDL_Delay(10)
            queue = messaging.get_messages()

        gameplay.state.floor.from_dict(json.loads(queue.get()))

    gameplay.state.players = []
    for i in range(num_players):
        new_player = Player(i, 200 + 200 * i, 350)
        gameplay.state.players.append(new_player)
        new_player.roomX = gameplay.state.floor.startingLocs[i][0]
        new_player.roomY = gameplay.state.floor.startingLocs[i][1]
        print("Starting room: %d %d" % (new_player.roomX, new_player.roomY))
        gameplay.state.floor.board[new_player.roomX][
            new_player.roomY].simulation.add_object(new_player.collider)

    gameplay.state.fullHeart = graphics.view.sprite_factory.from_file(
        "./assets/hearts.png").subsprite(graphics.rect.Rect(0, 0, 300, 300))

    gameplay.state.emptyHeart = graphics.view.sprite_factory.from_file(
        "./assets/hearts.png").subsprite(graphics.rect.Rect(600, 0, 300, 300))
    graphics.view.makeGameSubView()

    my_player = gameplay.state.players[gameplay.state.my_player_id]

    frame = 0
    last_phys_time = sdl2.SDL_GetTicks()
    while running == True:
        frame_start = sdl2.SDL_GetTicks()

        input_events = sdl2.ext.get_events()
        game_events = []

        for event in input_events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            else:
                if not ControlsState.should_process_input_event(event):
                    continue
                ControlsState.update_state(event)
                player_event = gameplay.state.players[
                    gameplay.state.my_player_id].processInputEvent(event)
                if player_event.params["code"] == "NONE":
                    continue
                game_events.append(player_event)
                messaging.broadcast(player_event.serialize().encode("utf-8"))

        messages = messaging.get_messages()
        while messages.qsize() > 0:
            msg = messages.get()
            game_events.append(GameEvent.deserialize(msg.decode("utf-8")))

        for event in game_events:
            if (event.params["type"] == "PLAYER"):
                gameplay.state.players[
                    event.params["player_id"]].processPlayerEvent(event)
            if (event.params["type"] == "STATUS"):
                if (event.params["kind"] == "ROOM"):
                    gameplay.state.floor.handle_update_event(event)

        for enemy in gameplay.state.floor.board[my_player.roomX][
                my_player.roomY].enemies:
            enemy.chooseNewDirection(gameplay.state.players, my_player.roomX,
                                     my_player.roomY)

        nearby_ps = []
        for player in gameplay.state.players:
            if nearby(player):
                nearby_ps.append(player.id)

        monster_update = gameplay.state.floor.get_update_event(
            my_player.roomX, my_player.roomY)
        monster_update_str = monster_update.serialize().encode("utf-8")
        if nearby_ps[0] == gameplay.state.my_player_id and len(nearby_ps) > 1:
            if frame % 30 == 0:
                for p in nearby_ps:
                    if nearby_ps[p] != gameplay.state.my_player_id:
                        messaging.send_to(p, monster_update_str)

        curr_time = sdl2.SDL_GetTicks()
        delta = curr_time - last_phys_time
        last_phys_time = curr_time

        gameplay.state.global_queue = Queue()
        gameplay.state.floor.board[my_player.roomX][
            my_player.roomY].simulation.step(delta / 1000)
        while not gameplay.state.global_queue.empty():
            update_dict = gameplay.state.global_queue.get()
            messaging.broadcast(update_dict.serialize().encode("utf-8"))
            if update_dict.params["player_id"] == gameplay.state.my_player_id and \
                    update_dict.params["code"] == "CHANGE_ROOM":
                messaging.broadcast(monster_update_str)

        for player in gameplay.state.players:
            if player.id != gameplay.state.my_player_id:
                if player.roomX == my_player.roomX and player.roomY == my_player.roomY:
                    gameplay.state.floor.board[player.roomX][
                        player.roomY].simulation.add_object(player.collider)

        graphics.view.render()

        frame_end = sdl2.SDL_GetTicks()
        remaining_time = (frame_start + FRAME_LENGTH) - frame_end
        if remaining_time > 0:
            sdl2.SDL_Delay(remaining_time)
        frame += 1

    sdl2.ext.quit()
Exemplo n.º 5
0
def main():
    if len(sys.argv) < 3:
        print("Please provide player file name and player id")
        sys.exit(1)

    my_player_id = None
    players_str = None
    with open(sys.argv[1], "r") as player_file:
        my_player_id = int(sys.argv[2])
        players_str = player_file.read()

    player_adds = players_str.split()
    num_players = len(player_adds)

    messaging = MessagingHandler()
    messaging.connect(player_adds, num_players, my_player_id)

    graphics.view.initView()

    running = True

    col = Color(123, 123, 123)

    players = []
    for i in range(num_players):
        players.append(Player(i, 50 * i, 50))

    sim = physics.Simulation()
    dg = graphics.view.sprite_factory.from_file("./assets/dungeon.png")
    r = dg.rect
    wall = physics.PhysObject(physics.Vec2(300, 300),
                              physics.Polygon.square(300, 300, 200, 200))
    player = players[0]
    sim.add_object(player.collider)
    player.collider.collision_type = physics.collision_types.dynamic
    sim.add_object(wall)
    while running == True:
        input_events = sdl2.ext.get_events()

        game_events = []

        for event in input_events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            else:
                if not ControlsState.should_process_input_event(event):
                    continue
                ControlsState.update_state(event)
                player_event = players[my_player_id].processInputEvent(event)
                if player_event.params["code"] == "NONE":
                    continue
                game_events.append(player_event)
                messaging.broadcast(player_event.serialize().encode("utf-8"))
        messages = messaging.get_messages()
        while messages.qsize() > 0:
            msg = messages.get()
            game_events.append(GameEvent.deserialize(msg.decode("utf-8")))

        for event in game_events:
            if (event.params["type"] == "PLAYER"):
                players[event.params["player_id"]].processPlayerEvent(event)
        #for player in players:
        #    player.update()
        sim.step(16 / 1000)
        graphics.view.raw_renderer.clear(col)
        #graphics.view.sprite_renderer.draw_sprite(dg, wall.pos.x, wall.pos.y)
        for player in players:
            player.render(graphics.view.sprite_renderer)

        graphics.view.sprite_renderer.draw_collision_boxes(sim)
        graphics.view.raw_renderer.present()
        graphics.view.window.refresh()
        sdl2.SDL_Delay(16)
Exemplo n.º 6
0
def main():
    if len(sys.argv) < 3:
        print("Please provide player file name and player id")
        sys.exit(1)

    gameplay.state.my_player_id = None
    players_str = None
    with open(sys.argv[1], "r") as player_file:
        gameplay.state.my_player_id = int(sys.argv[2])
        players_str = player_file.read()

    player_adds = players_str.split()
    num_players = len(player_adds)

    messaging = MessagingHandler()
    messaging.connect(player_adds, num_players, gameplay.state.my_player_id)

    running = True

    graphics.view.initView()

    gameplay.state.floor = Floor()
    gameplay.state.floor.genFloor(3, 0)
    gameplay.state.players = []
    for i in range(num_players):
        new_player = Player(i, 200 + 200 * i, 350)
        gameplay.state.players.append(new_player)
        new_player.roomX = gameplay.state.floor.startingLocs[0][0]
        new_player.roomY = gameplay.state.floor.startingLocs[0][1]
        print("Starting room: %d %d" % (new_player.roomX, new_player.roomY))
        gameplay.state.floor.board[new_player.roomX][new_player.roomY].simulation.add_object(new_player.collider)

    graphics.view.makeGameSubView()

    last_phys_time = sdl2.SDL_GetTicks()
    while running == True:
        frame_start = sdl2.SDL_GetTicks()

        input_events = sdl2.ext.get_events()
        game_events = []

        for event in input_events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            else:
                if not ControlsState.should_process_input_event(event):
                    continue
                ControlsState.update_state(event)
                player_event = gameplay.state.players[gameplay.state.my_player_id].processInputEvent(event)
                if player_event.params["code"] == "NONE":
                    continue
                game_events.append(player_event)
                messaging.broadcast(player_event.serialize().encode("utf-8"))

        messages = messaging.get_messages()
        while messages.qsize() > 0:
            msg = messages.get()
            game_events.append(GameEvent.deserialize(msg.decode("utf-8")))

        for event in game_events:
            if (event.params["type"] == "PLAYER"):
                gameplay.state.players[event.params["player_id"]].processPlayerEvent(event)
            if (event.params["type"] == "STATUS"):
                room = gameplay.state.floor.board[event.params["room_x"]["room_y"]]
                if event.params["kind"] == "bullet":
                    print("UPDATING BULLET")
                    obj = room.projectiles[event.params["id"]]
                    obj.collider.pos.from_dict(event.params["pos"])
                    obj.collider.vel.from_dict(event.params["vel"])

        curr_time = sdl2.SDL_GetTicks()
        delta = curr_time - last_phys_time
        last_phys_time = curr_time
        roomX = 0
        for column in gameplay.state.floor.board:
            roomY = 0
            for room in column:
                if room is not None:
                    for p in [x for x in room.projectiles.keys() if x in gameplay.state.responsible_for]:
                        b = room.projectiles[p]
                        heartbeat_dict = {
                            "type": "STATUS",
                            "kind": "bullet",
                            "player_id": b.id,
                            "room_id": (roomX, roomY),
                            "room_x": roomX,
                            "room_y": roomY,
                            "id": b.id,
                            "pos": b.collider.pos.to_dict(),
                            "vel": b.collider.pos.to_dict(),
                        }
                        print(heartbeat_dict)
                        messaging.broadcast(player_event.serialize().encode("utf-8"))
                    room.simulation.step(delta / 1000)
                roomY += 1
            roomX += 1

        graphics.view.render()

        frame_end = sdl2.SDL_GetTicks()
        remaining_time = (frame_start + FRAME_LENGTH) - frame_end
        if remaining_time > 0:
            sdl2.SDL_Delay(remaining_time)

    sdl2.ext.quit()
Exemplo n.º 7
0
def main():
    if len(sys.argv) < 3:
        print("Please provide player file name and player id")
        sys.exit(1)

    gameplay.state.my_player_id = None
    players_str = None
    with open(sys.argv[1], "r") as player_file:
        gameplay.state.my_player_id = int(sys.argv[2])
        players_str = player_file.read()

    player_adds = players_str.split()
    num_players = len(player_adds)

    messaging = MessagingHandler()
    messaging.connect(player_adds, num_players, gameplay.state.my_player_id)

    graphics.view.initView()
    graphics.view.makeGameSubView()
    running = True

    gameplay.state.floor = Floor()
    gameplay.state.floor.genFloor(10, 25)
    gameplay.state.players = []
    sim = Simulation()

    for i in range(num_players):
        gameplay.state.players.append(Player(i, 50 * i, 50))
        sim.add_object(gameplay.state.players[i].collider)

    gameplay.state.floor.board[0][0] = Room()
    gameplay.state.floor.board[0][0].enemies = []
    gameplay.state.floor.board[0][0].enemies.append(Monster(0, 100, 100))
    sim.add_object(gameplay.state.floor.board[0][0].enemies[0].collider)

    last_phys_time = sdl2.SDL_GetTicks()
    while running == True:
        frame_start = sdl2.SDL_GetTicks()

        input_events = sdl2.ext.get_events()
        game_events = []

        for event in input_events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            else:
                if not ControlsState.should_process_input_event(event):
                    continue
                ControlsState.update_state(event)
                player_event = gameplay.state.players[gameplay.state.my_player_id].processInputEvent(event)
                if player_event.params["code"] == "NONE":
                    continue
                game_events.append(player_event)
                messaging.broadcast(player_event.serialize().encode("utf-8"))

        for enemy in gameplay.state.floor.board[0][0].enemies:
            enemy.chooseNewDirection(gameplay.state.players)

        messages = messaging.get_messages()
        while messages.qsize() > 0:
            msg = messages.get()
            game_events.append(GameEvent.deserialize(msg.decode("utf-8")))

        for event in game_events:
            if (event.params["type"] == "PLAYER"):
                gameplay.state.players[event.params["player_id"]].processPlayerEvent(event)

        curr_time = sdl2.SDL_GetTicks()
        delta = curr_time - last_phys_time
        last_phys_time = curr_time
        sim.step(delta / 1000)

        graphics.view.render()

        frame_end = sdl2.SDL_GetTicks()
        remaining_time = (frame_start + FRAME_LENGTH) - frame_end
        if remaining_time > 0:
            sdl2.SDL_Delay(remaining_time)

    sdl2.ext.quit()