Exemple #1
0
    def __init__(self, size):
        self.background = pygame.Surface(size)  # make a background surface
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        font = pygame.font.Font(None, 40)

        self.score = Score(font)

        self.walls = [Wall((10, 10), (790, 20)), Wall((10, 580), (790, 590))]

        self.bats = []

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = K_w
        control_scheme_1.down = K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = K_UP
        control_scheme_2.down = K_DOWN

        self.bats.append(Bat((10, 200), control_scheme_1))
        self.bats.append(Bat((780, 200), control_scheme_2))

        self.ball = Ball((400, 300))
Exemple #2
0
 def __init__(self, name, side, engine, speed=1):
     self.name = name
     self._score = Score()
     self.engine = engine
     self.side = side
     self.pad = Pad(self.side, speed, self.engine)
     if self.is_at_left():
         self.goal = Goal(790, self)
     else:
         self.goal = Goal(0, self)
Exemple #3
0
def main(screen):

    # create the cast {key: tag, value: list}
    cast = {}

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y - 1)
    position = Point(x, y)
    paddle = Player()
    paddle.set_position(position)
    cast["paddle"] = [paddle]

    cast["brick"] = []
    for x in range(5, 75):
        for y in range(2, 6):
            position = Point(x, y)
            brick = Brick()
            brick.set_text("*")
            brick.set_position(position)
            cast["brick"].append(brick)

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y / 2)
    position = Point(x, y)
    velocity = Point(1, -1)
    ball = Ball()
    ball.set_text("@")
    ball.set_position(position)
    ball.set_starting_position(position)
    ball.set_velocity(velocity)
    cast["ball"] = [ball]
    score = Score()
    score.set_position(Point(4, 0))
    cast["score"] = [score]
    lives = Lives()
    lives.set_position(Point(67, 0))
    cast["lives"] = [lives]

    # create the script {key: tag, value: list}
    script = {}

    input_service = InputService(screen)
    output_service = OutputService(screen)
    control_actors_action = ControlActorsAction(input_service)
    move_actors_action = MoveActorsAction()
    handle_collisions_acition = HandleCollisionsAction()
    draw_actors_action = DrawActorsAction(output_service)

    script["input"] = [control_actors_action]
    script["update"] = [move_actors_action, handle_collisions_acition]
    script["output"] = [draw_actors_action]

    # start the game
    director = Director(cast, script)
    director.start_game()
Exemple #4
0
 def __init__(self, input_service, output_service):
     """The class constructor.
     
     Args:
         self (Director): an instance of Director.
     """
     self.buffer = Buffer()
     self._input_service = input_service
     self._keep_playing = True
     self._output_service = output_service
     self._score = Score()
     self._words = Word()
Exemple #5
0
    def __init__(self, input_service, output_service):
        """Class constructor

        Args:
            self (Director): An instance of director
        """
        self._input_service = input_service
        self._keep_playing = True
        self._output_service = output_service
        self._score = Score()
        self._word = WordActor()
        self.user_word = Actor()
        self.user_word._position._y = constants.MAX_Y + 1
Exemple #6
0
 def start_watch(self, level):
     self.dj.enter_level()
     self.load_level(level)
     self.state = "RUNNING"
     self.moves = 0
     self.auto_speed = 0
     self.solver_failed = False
     self.move_num = Score([1256, 45])
     self.display_hint = False
     self.startSolved()
     if not self.solver_failed:
         self.solve_timer = Timer(1.5)
         self.display_hint = True
Exemple #7
0
 def start_normal(self, level):
     self.display_hint = False
     self.dj.enter_level()
     self.load_level(level)
     self.state = "RUNNING"
     self.moves = 0
     self.selected = -1
     '''
     solver_thread = Thread(target=self.update_hint)
     solver_thread.start()
     '''
     self.saved_moves = []
     self.move_num = Score([1256, 45])
     self.undo_num = Score([1256, 115])
Exemple #8
0
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._word = Word()
        self._input_service = input_service
        self._keep_playing = True
        self._output_service = output_service
        self._score = Score()
        self._speed = Speed()
        self._guess = Guess()
        self._actor = Actor()

        self.correct = 0
Exemple #9
0
def initialize_game_elements():
    """
    Creates all class instances needed for the game, then saves all instances into a dictionary

    :return: type: dict
    A dictionary containing all the class instances needed for the game to function
    """
    # Initialize first & second base
    base1 = Base(0, DISPLAY_HEIGHT - Base.height)
    base2 = Base(Base.width, DISPLAY_HEIGHT - Base.height)

    # Initialize bird
    bird = Bird((DISPLAY_WIDTH / 2) - Bird.width, DISPLAY_HEIGHT / 2)

    # Initialize pipes
    pipe1 = Pipe(DISPLAY_WIDTH * 2)
    pipe2 = Pipe(pipe1.x + Pipe.interval)

    # Initialize score
    score = Score()

    return {
        "base": [base1, base2],
        "bird": bird,
        "pipe": [pipe1, pipe2],
        "score": score
    }
Exemple #10
0
    def load_next_level(self):
        level_number = 2
        self.cast = {}

        player = Player()
        self.cast['player'] = [player]

        items = Items()
        self.cast['items'] = [items]

        background = BackgroundMaker(self.cast)
        maps = MapMaker(self.cast, level_number)

        score = Score()
        self.cast["score"] = [score]

        self.script = {}

        self.output_services = OutputServices()
        self.input_service = InputServices(self.cast)
        self.gravity_engine = Gravity(self.cast)

        handle_collisions = DoCollisionsAction(self.cast, self)
        screen_scrolling = ScreenScrollAction()

        control_actors = ControlActorsAction(self.input_service,
                                             self.gravity_engine)
        do_outputs = DrawActorsAction(self.output_services, screen_scrolling)
        do_updates = DoUpdatesAction(self.gravity_engine)

        self.script["input"] = [control_actors]
        self.script["update"] = [
            do_updates, handle_collisions, screen_scrolling
        ]
        self.script["output"] = [do_outputs]
Exemple #11
0
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._input_service = input_service
        self._output_service = output_service
        self._buffer = Buffer()
        self._word = Word('test')
        self._current_words = []
        self._text_words = []
        self._inputted_letter = ''
        self._score = Score()

        self._keep_playing = True
    def __play_round(self, players=list):
        """Runs a round of play and returns a winner.

        Args:
            self (Director): an instance of Director.
            players (list): a list of player names.
        """
        code = self._board.generate_code()
        self._player = Player(players)
        self._score = Score(players)
        self.__stop_round = False

        while not self.__stop_round:
            for player in players:
                if len(players) > 1:
                    self._console.confirm_start(player)

                history = self._player.get_moves(player)
                stats = self._score.get_stats(player)

                guess, elapsed = self._console.play_turn(
                    player, code, history, stats)
                self._score.record_turn(elapsed, player)

                while not self._board.validate_guess(guess):
                    stats = self._score.get_stats(player)
                    guess, elapsed = self._console.play_turn(player,
                                                             code,
                                                             history,
                                                             stats,
                                                             redo=True)
                    self._score.record_turn(elapsed, player)

                if guess == code:
                    stats = self._score.get_stats(player)
                    self._score.update_board(player, stats)

                    self.__end_round(player, stats)
                    self.__stop_round = True
                    self._console.restart_menu()
                    break

                hint = self._board.create_hint(code, guess)
                self._console.show_hint(hint)

                move_hint = (guess, hint)
                self._player.record_move(player, move_hint)
Exemple #13
0
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """

        self.words = []
        for x in range(5):  #Generates 5 word actors
            newWord = Word()
            self.words.append(newWord)

        self._input_service = input_service
        self._keep_playing = True
        self._output_service = output_service
        self._score = Score()
        self._userinput = UserInput()
        self._timer = Timer()
def main(screen):

    # create the cast {key: tag, value: list}
    cast = {}

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y - 1)
    position = Point(x, y)
    paddle = Actor()
    paddle.set_text("===========")  # 11 wide
    paddle.set_position(position)
    cast["paddle"] = [paddle]

    cast["brick"] = []
    for x in range(5, 75, 3):
        for y in range(2, 8, 1):
            position = Point(x, y)
            brick = Actor()
            brick.set_text("##")
            brick.set_position(position)
            cast["brick"].append(brick)

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y / 2)
    position = Point(x, y)
    velocity = Point(1, -1)
    ball = Actor()
    ball.set_text("@")
    ball.set_position(position)
    ball.set_velocity(velocity)
    cast["ball"] = [ball]

    #Add points for broken bricks
    score = Score()
    cast["score"] = [score]

    # create the script {key: tag, value: list}
    script = {}

    input_service = InputService(screen)
    output_service = OutputService(screen)
    control_actors_action = ControlActorsAction(input_service)
    move_actors_action = MoveActorsAction()
    handle_collisions_acition = HandleCollisionsAction()
    draw_actors_action = DrawActorsAction(output_service)

    script["input"] = [control_actors_action]
    script["update"] = [move_actors_action, handle_collisions_acition]
    script["output"] = [draw_actors_action]

    # start the game
    director = Director(cast, script)
    director.start_game()
Exemple #15
0
 def __init__(self, input_ser, output_ser):
     """The class constructor.
     
     Args:
         self (Director): an instance of Director.
     """
     self._input_service = input_ser
     self._output_service = output_ser
     self._keep_playing = True
     self._player = Player()
     self._words = []
     self._score = Score()
     for item in range(5):
         self._words.append(Word())
Exemple #16
0
    def __init__(self):
        init()
        font.init()
        display.set_caption(TITLE)
        key.set_repeat()

        self.playing = False

        self.screen = display.set_mode((WIDTH, HEIGHT))

        self.clock = time.Clock()
        self.dt = self.clock.tick(FPS) / 1000

        self.labels = list()
        self.infos = list()

        self.all_sprites = Group()

        self.adventure = Home(self)

        self.camera = Camera(self.adventure.map.width, self.adventure.map.height)
        self.score = Score("Renato")

        self.game_over = False
Exemple #17
0
class PongGame:
    def __init__(self, size):
        self.background = pygame.Surface(size)  # make a background surface
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        font = pygame.font.Font(None, 40)

        self.score = Score(font)

        self.walls = [Wall((10, 10), (790, 20)), Wall((10, 580), (790, 590))]

        self.bats = []

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = K_w
        control_scheme_1.down = K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = K_UP
        control_scheme_2.down = K_DOWN

        self.bats.append(Bat((10, 200), control_scheme_1))
        self.bats.append(Bat((780, 200), control_scheme_2))

        self.ball = Ball((400, 300))

    def process_event(self, event):
        for bat in self.bats:
            bat.process_event(event)

    def update(self, time_delta):
        for bat in self.bats:
            bat.update(time_delta)

        self.ball.update(time_delta, self.bats, self.walls)

        if self.ball.position[0] < 0:
            self.ball.reset()
            self.score.increase_player_2_score()
        elif self.ball.position[0] > 800:
            self.ball.reset()
            self.score.increase_player_1_score()

    def draw(self, surface):
        surface.blit(self.background, (0, 0))

        for wall in self.walls:
            wall.render(surface)

        for bat in self.bats:
            bat.render(surface)

        self.ball.render(surface)
        self.score.render(surface)
Exemple #18
0
    def __init__(self):
        """Initalize the Window class
        Args:
            self (Window): an instance of Window
        Contributors:
            Reed Hunsaker
            Isabel Aranguren
        """
        super().__init__(constants.X_CONSTANT, constants.Y_CONSTANT,
                         constants.TITLE)

        self.master_volume = constants.DEFAULT_VOLUME

        self.score = Score()
        self.start_view = MainView()
        self.background_music = arcade.Sound(constants.MAIN_SCREEN_SOUND)
        self.background_music.play(self.master_volume, loop=True)
Exemple #19
0
class Player:
    def __init__(self, name, side, engine, speed=1):
        self.name = name
        self._score = Score()
        self.engine = engine
        self.side = side
        self.pad = Pad(self.side, speed, self.engine)
        if self.is_at_left():
            self.goal = Goal(790, self)
        else:
            self.goal = Goal(0, self)

    def win_point(self):
        self._score.win_point()

    def handle(self, event):
        self.pad.handle(event)

    def points(self):
        return self._score.points()

    def partials(self):
        return self._score.partials()

    def new_set(self):
        self._score.new_set()

    def win_set(self):
        self._score.win_set()

    def sets(self):
        return self._score.sets()

    def is_at_left(self):
        return self.side == 'left'

    def beats(self, other):
        return self.points() > other.points()
    def __init__(self):
        """ Declares variables for the GameView class
        Args:
            self (Gameview): an instance of Gameview
        Contributors:
            Reed Hunsaker
            Adrianna Lund
            Isabel Aranguren
            Jordan McIntyre
            Juliano Nascimiento
        """
        super().__init__()

        self._score = Score()
        self.texture = arcade.load_texture(constants.BACKGROUND)
        self.game_ending = False
        self.name = ""

        # physics engines
        self.physics_engine = None
        self.physics_engine2 = None
        self.physics_engine3 = None
        self.physics_engine4 = None

        # sprite lists
        self.bullet_list = None
        self.explosions_list = None
        self.explosion_texture_list = []

        # sounds
        self.powerup_sound = arcade.load_sound(constants.POWERUPS_SOUND)
        self.powerdown_sound = arcade.load_sound(constants.POWERDOWN_SOUND)
        self.tank_explode = arcade.load_sound(constants.EXPLOSION_SOUND)

        # explosion details
        self.columns = 16
        self.count = 8
        self.sprite_width = 256
        self.sprite_height = 256
        self.file_name = ":resources:images/spritesheets/explosion.png"
        self.explosion_texture_list = arcade.load_spritesheet(
            self.file_name, self.sprite_width, self.sprite_height,
            self.columns, self.count)
Exemple #21
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller

    Attributes:
        food (Food): The snake's target.
        input_service (InputService): The input mechanism.
        keep_playing (boolean): Whether or not the game can continue.
        output_service (OutputService): The output mechanism.
        score (Score): The current score.
        snake (Snake): The player or snake.
    """
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._buffer = Buffer()
        self._input_service = input_service
        self._keep_playing = True
        self._output_service = output_service
        self._score = Score()
        self._words = Words()
        self._slow = 0

    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()
            sleep(constants.FRAME_LENGTH)

    def _get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means getting the desired direction and moving the snake.

        Args:
            self (Director): An instance of Director.
        """
        self._buffer.add_letter(letter)
        letter = self._input_service.get_letter()
        self._words.move_words()

    def _do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means checking for a collision and updating the score.

        Args:
            self (Director): An instance of Director.
        """
        self._add_new_words()
        self._handle_matching_words()

    def _do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means checking if there are stones left and declaring 
        the winner.

        Args:
            self (Director): An instance of Director.
        """
        self._output_service.clear_screen()
        self._output_service.draw_actor(self._buffer)
        self._output_service.draw_actors(self._words.get_all())
        self._output_service.draw_actor(self._score)
        self._output_service.flush_buffer()

    def _handle_body_collision(self):  #Not sure with this reference help
        """Handles collisions between the snake's head and body. Stops the game 
        if there is one.

        Args:
            self (Director): An instance of Director.
        """
        head = self._snake.get_head()
        body = self._snake.get_body()
        for segment in body:
            if head.get_position().equals(segment.get_position()):
                self._keep_playing = False
                break

    def _handle_food_collision(self):  #See comment above.
        """Handles collisions between the snake's head and the food. Grows the 
        snake, updates the score and moves the food if there is one.

        Args:
            self (Director): An instance of Director.
        """
        head = self._snake.get_head()
        if head.get_position().equals(self._food.get_position()):
            points = self._food.get_points()
            for n in range(points):
                self._snake.grow_tail()
            self._score.add_points(points)
            self._food.reset()
Exemple #22
0
class UI:
    def __init__(self):
        self.state = "MAINMENU"
        self.algorithm = 0
        self.hint_available = True
        self.auto_solving = False
        self.paused = False
        self.auto_speed = 0
        self.init_screen()
        self.load_other()
        self.build_menu()
        self.build_main_menu()
        self.build_setting_menu()
        self.build_music_player()
        self.build_end_screen()
        self.timer = Timer(mouse_timeout)
        self.active = True

    # Init functions
    def init_screen(self):
        self.screen = pygame.display.set_mode((screen_width, screen_height))

    def build_menu(self):
        self.menu = GameMenu(levels)

    def build_music_player(self):
        self.dj = MusicPlayer()

    def build_main_menu(self):
        self.main_menu = Menu()

    def build_setting_menu(self):
        self.settings = SettingsMenu()

    def build_end_screen(self):
        self.end_screen = EndScreen()

    # Load functions
    def load_bg(self):
        self.bg = pygame.image.load('assets/img/lab.jpg')

    def load_level(self, num):
        if hasattr(self, 'curGame'):
            del self.cur_game
        level = copy.deepcopy(levels[str(num)])
        self.cur_game = Game(level)
        self.create_game()

    def load_tubes(self, num):
        self.flasks = pygame.sprite.Group()

    def load_other(self):
        self.load_bg()
        self.load_quit()
        self.load_undo()
        self.load_move_count()
        self.load_undo_count()
        self.load_hint()
        self.load_auto_solve()

    def load_auto_solve(self):
        self.load_speed()
        self.load_pause()
        self.load_algorithm_fail()

    def load_speed(self):

        speed_holder = pygame.image.load("assets/img/holders/speedHolder.png")
        value_holder = pygame.image.load("assets/img/holders/prevNext.png")

        font = pygame.font.SysFont("Arial", 45)
        font2 = pygame.font.SysFont("Arial", 40)
        speed = text_to_sprite("Speed", speed_holder, (230, 230, 230),
                               [1075, 125], font)
        point_five = text_to_sprite("x0.5", value_holder, (230, 230, 230),
                                    [1250, 137.5], font2)
        normal = text_to_sprite("x1", value_holder, (230, 230, 230),
                                [1250, 137.5], font2)
        x2 = text_to_sprite("x2", value_holder, (230, 230, 230), [1250, 137.5],
                            font2)
        x4 = text_to_sprite("x4", value_holder, (230, 230, 230), [1250, 137.5],
                            font2)
        x8 = text_to_sprite("x8", value_holder, (230, 230, 230), [1250, 137.5],
                            font2)

        self.speed_holder = pygame.sprite.GroupSingle(speed)
        self.speeds = []
        self.speeds.append(pygame.sprite.GroupSingle(normal))
        self.speeds.append(pygame.sprite.GroupSingle(x2))
        self.speeds.append(pygame.sprite.GroupSingle(x4))
        self.speeds.append(pygame.sprite.GroupSingle(x8))
        self.speeds.append(pygame.sprite.GroupSingle(point_five))

    def load_pause(self):

        holder = pygame.image.load("assets/img/holders/speedHolder.png")
        font = pygame.font.SysFont("Arial", 40)
        pause = text_to_sprite("Pause", holder, (230, 230, 230), [1075, 225],
                               font)
        resume = text_to_sprite("Resume", holder, (230, 230, 230), [1075, 225],
                                font)
        self.pauseButton = pygame.sprite.GroupSingle(pause)
        self.resumeButton = pygame.sprite.GroupSingle(resume)

    def load_undo(self):
        undo_img = load_sprite("assets/img/buttons/undo.png")
        undo_img.rect.left = 1250
        undo_img.rect.top = 200
        self.undoB = pygame.sprite.GroupSingle(undo_img)

    def load_quit(self):
        quit_img = load_sprite("assets/img/buttons/menu.png")
        quit_img.rect.left = 20
        quit_img.rect.top = 20
        self.quit = pygame.sprite.GroupSingle(quit_img)

    def load_move_count(self):
        move_holder = load_sprite("assets/img/holders/numberBox.png")
        move_holder.rect.left, move_holder.rect.top = [1250, 50]
        self.moveHolder = pygame.sprite.GroupSingle(move_holder)
        move_count = load_sprite("assets/img/holders/moveCount.png")
        move_count.rect.left, move_count.rect.top = [1000, 45]
        self.moveCount = pygame.sprite.GroupSingle(move_count)

    def load_undo_count(self):
        undo_holder = load_sprite("assets/img/holders/numberBox.png")
        undo_holder.rect.left, undo_holder.rect.top = [1250, 120]
        self.undoHolder = pygame.sprite.GroupSingle(undo_holder)
        undo_count = load_sprite("assets/img/holders/undoCount.png")
        undo_count.rect.left, undo_count.rect.top = [1000, 115]
        self.undoCount = pygame.sprite.GroupSingle(undo_count)

    def load_hint(self):
        hint_up = load_sprite("assets/img/arrow_up.png")
        self.hint_up = pygame.sprite.GroupSingle(hint_up)
        hint_down = load_sprite("assets/img/arrow_down.png")
        self.hint_down = pygame.sprite.GroupSingle(hint_down)

        hint_b = load_sprite("assets/img/buttons/hint.png")
        hint_b.rect.left, hint_b.rect.top = [1250, 280]
        self.hint_b = pygame.sprite.GroupSingle(hint_b)

        hint_no = load_sprite("assets/img/buttons/no-hint.png")
        hint_no.rect.left, hint_no.rect.top = [1250, 280]
        self.hint_no = pygame.sprite.GroupSingle(hint_no)

    def load_algorithm_fail(self):
        self.solver_failed = False
        holder = pygame.image.load("assets/img/holders/failHolder.png")
        font = pygame.font.SysFont("Arial", 40)
        alg_fail = text_to_sprite(
            "Algorithm couldn't reach a solution in due time", holder,
            (230, 230, 230), [300, 400], font)

        self.alg_fail = pygame.sprite.GroupSingle(alg_fail)

    ## Draw functions

    def draw_screen(self):
        self.screen.blit(self.bg, (0, 0))

    def draw_main_menu(self):
        self.main_menu.draw(self.screen)

    def draw_game_menu(self):
        self.menu.draw(self.screen)

    def draw_settings_menu(self):
        self.settings.draw(self.screen)

    def draw_quit(self):
        self.quit.draw(self.screen)

    def draw_undo(self):
        self.undoB.draw(self.screen)

    def draw_flasks(self):
        for flask in self.tubes:
            flask.draw(self.screen)

    def draw_hint(self):
        if self.hint_available:
            self.hint_b.draw(self.screen)
        else:
            self.hint_no.draw(self.screen)

    def draw_solved_hint(self):
        if self.display_hint:
            self.hint_up.draw(self.screen)
            self.hint_down.draw(self.screen)

    def drawMoveCount(self):
        self.moveCount.draw(self.screen)
        self.moveHolder.draw(self.screen)
        self.move_num.draw(self.screen)

    def drawUndoCount(self):
        self.undoCount.draw(self.screen)
        self.undoHolder.draw(self.screen)
        self.undo_num.draw(self.screen)

    def drawRun(self):
        if self.auto_solving:
            self.draw_watch()
        else:
            self.draw_play()

    def draw_watch(self):
        self.draw_solved_hint()
        self.draw_flasks()
        self.draw_quit()
        self.drawMoveCount()
        self.draw_speed()
        self.draw_pause()
        if self.solver_failed:
            self.alg_fail.draw(self.screen)

    def draw_play(self):
        self.draw_hint()
        self.draw_solved_hint()
        self.draw_flasks()
        self.draw_quit()
        self.draw_undo()
        self.drawMoveCount()
        self.drawUndoCount()

    def draw_pause(self):
        if self.paused:
            self.resumeButton.draw(self.screen)
        else:
            self.pauseButton.draw(self.screen)

    def draw_end(self):
        if self.auto_solving:
            self.end_screen.draw_solved(self.screen, self.move_num.score)
        else:
            self.end_screen.draw(self.screen, self.move_num.score,
                                 self.undo_num.score)

    def draw_speed(self):
        self.speed_holder.draw(self.screen)
        self.speeds[self.auto_speed].draw(self.screen)

    # Collision functions

    def check_flasks_cols(self, mouse_pos):
        i = 0
        for tube in self.tubes:
            if tube.check_mouse_col(mouse_pos):
                return i
            i += 1
        return -1

    def check_quit(self, mouse_pos):
        return self.quit.sprite.rect.collidepoint(mouse_pos)

    def check_undo(self, mouse_pos):
        return self.undoB.sprite.rect.collidepoint(mouse_pos)

    def check_hint(self, mouse_pos):
        return self.hint_b.sprite.rect.collidepoint(mouse_pos)

    def check_run_cols(self, mouse_pos):
        select = self.check_flasks_cols(mouse_pos)
        if select > -1:
            self.make_move(select)
            if self.check_completed():
                self.end_game()
        elif self.check_undo(mouse_pos):
            self.undo()
        elif self.check_quit(mouse_pos):
            self.return_to_menu()
        elif self.check_hint(mouse_pos):
            '''solver_thread = Thread(target=self.update_hint)
            solver_thread.start()'''
            self.update_hint()
            self.display_hint = True
            self.dj.click_hint()

    def check_solve_cols(self, mouse_pos):
        if self.check_quit(mouse_pos):
            self.return_to_menu()
        self.check_speed(mouse_pos)
        self.check_pause(mouse_pos)

    def check_speed(self, mouse_pos):
        if self.solver_failed:
            return
        if self.speeds[self.auto_speed].sprite.rect.collidepoint(mouse_pos):
            self.auto_speed += 1
            if self.auto_speed > 4:
                self.auto_speed = 0
                self.solve_timer.update_timer(1.5)
            elif self.auto_speed == 1:
                self.solve_timer.update_timer(0.75)
            elif self.auto_speed == 2:
                self.solve_timer.update_timer(0.375)
            elif self.auto_speed == 3:
                self.solve_timer.update_timer(0.19)
            elif self.auto_speed == 4:
                self.solve_timer.update_timer(3)

    def check_pause(self, mouse_pos):
        if self.solver_failed:
            return

        if self.paused:
            if self.resumeButton.sprite.rect.collidepoint(mouse_pos):
                self.paused = False
                self.solve_timer.start_timer()
        else:
            if self.pauseButton.sprite.rect.collidepoint(mouse_pos):
                self.paused = True

    def check_back_to_menu(self, mouse_pos):

        if self.end_screen.check_back_col(mouse_pos):
            self.return_to_menu()

    # Checking functions
    def check_completed(self):
        for tube in self.tubes:
            if not tube.check_done():
                return False
        return True

    def check_mouse_timeout(self, mouse):
        if (mouse):
            if (self.timer.check_timer()):
                self.timer.start_timer()
                return True
        return False

    # Run functions

    def run(self):
        self.draw_screen()
        if self.state == "MAINMENU":
            self.run_main_menu()
        elif self.state == "SETTINGS":
            self.run_settings_menu()
        elif self.state == "GAMEMENU":
            self.run_game_menu()
        elif self.state == "RUNNING":
            self.run_level()
        elif self.state == "END":
            self.run_end()

    def run_main_menu(self):
        self.draw_main_menu()
        mouse = pygame.mouse.get_pressed()[0]
        if self.check_mouse_timeout(mouse):
            select = self.main_menu.check_menu_cols()
            if select == 0:
                self.active = False

            elif select == 1:
                self.auto_solving = False
                self.level_selection()
            elif select == 2:
                self.auto_solving = True
                self.level_selection()
            elif select == 3:
                self.settings_menu()

    def run_game_menu(self):
        self.draw_game_menu()
        mouse = pygame.mouse.get_pressed()[0]
        if self.check_mouse_timeout(mouse):
            select = self.menu.check_menu_cols()
            if select == 0:
                self.return_to_main_menu()
            elif select > 0:
                self.start_game(select)
            elif select == -2:
                self.dj.clicked_button()

    def run_settings_menu(self):
        self.draw_settings_menu()
        mouse = pygame.mouse.get_pressed()[0]
        if self.check_mouse_timeout(mouse):
            select = self.settings.check_menu_cols()
            if select == 0:
                self.return_to_main_menu()
            elif select == 1:
                self.dj.switch_sfx()
            elif select == 2:
                self.dj.switch_music()
            elif select > 2:
                self.algorithm = select - 3

    def run_level(self):
        self.drawRun()

        mouse = pygame.mouse.get_pressed()[0]
        if self.check_mouse_timeout(mouse):
            mouse_pos = pygame.mouse.get_pos()
            if self.auto_solving:
                self.check_solve_cols(mouse_pos)
            else:
                self.check_run_cols(mouse_pos)
        if self.auto_solving and not self.solver_failed:
            if self.solve_timer.check_timer() and not self.paused:
                self.play_solved()

    def run_end(self):
        self.draw_end()
        mouse = pygame.mouse.get_pressed()[0]
        if self.check_mouse_timeout(mouse):
            mouse_pos = pygame.mouse.get_pos()
            self.check_back_to_menu(mouse_pos)

    # Level functions

    def create_game(self):
        if hasattr(self, 'tubes'):
            del self.tubes
        self.tubes = []
        x = 50
        y = 650

        for tube in self.cur_game.tubes:
            flask = Flask(tube, [x, y])
            self.tubes.append(flask)
            x += 112

    def start_game(self, level):
        if self.auto_solving:
            self.start_watch(level)
        else:
            self.start_normal(level)

    def start_watch(self, level):
        self.dj.enter_level()
        self.load_level(level)
        self.state = "RUNNING"
        self.moves = 0
        self.auto_speed = 0
        self.solver_failed = False
        self.move_num = Score([1256, 45])
        self.display_hint = False
        self.startSolved()
        if not self.solver_failed:
            self.solve_timer = Timer(1.5)
            self.display_hint = True

    def start_normal(self, level):
        self.display_hint = False
        self.dj.enter_level()
        self.load_level(level)
        self.state = "RUNNING"
        self.moves = 0
        self.selected = -1
        '''
        solver_thread = Thread(target=self.update_hint)
        solver_thread.start()
        '''
        self.saved_moves = []
        self.move_num = Score([1256, 45])
        self.undo_num = Score([1256, 115])

    def return_to_main_menu(self):
        self.state = "MAINMENU"

    def level_selection(self):
        self.state = "GAMEMENU"

    def return_to_menu(self):
        self.dj.in_menu()
        self.state = "GAMEMENU"
        self.selected = -1

    def settings_menu(self):
        self.state = "SETTINGS"

    def end_game(self):
        self.state = "END"
        self.selected = -1

    # Game functions

    def make_move(self, tube):
        if tube == self.selected:
            self.deselect()
        elif self.selected >= 0:
            if self.cur_game.move_ball(self.selected, tube):
                self.successful_move(tube)
        else:
            self.select(tube)

    def successful_move(self, tube):
        self.move_num.increase_score()
        ball = self.tubes[self.selected].remove_ball()
        if self.tubes[tube].add_ball(ball):
            self.dj.complete_tube()
        self.saved_moves.append([self.selected, tube])
        '''
        solver_thread = Thread(target=self.update_hint)
        solver_thread.start()
        '''
        self.deselect()
        self.display_hint = False

    def undo(self):
        if self.saved_moves:
            self.undo_num.increase_score()
            self.move_num.decrease_score()
            last_move = self.saved_moves.pop()
            self.undo_move(last_move)

    def undo_move(self, move):
        self.cur_game.move_ball(move[1], move[0])

        ball = self.tubes[move[1]].remove_ball()
        self.tubes[move[0]].add_ball(ball)
        '''
        solver_thread = Thread(target=self.update_hint)
        solver_thread.start()
        '''

    @timeout(20)
    def get_result(self, init_state):

        if self.algorithm == 0:
            return solver(init_state, Algorithm.A_STAR, 30)
        elif self.algorithm == 1:
            return solver(init_state, Algorithm.GREEDY, 30)
        elif self.algorithm == 2:
            return solver(init_state, Algorithm.DFS, 60)
        elif self.algorithm == 3:
            return solver(init_state, Algorithm.BFS, 15)
        elif self.algorithm == 4:
            return ids(init_state, 60)

    def startSolved(self):
        init_state = Node(self.cur_game)
        try:
            result = self.get_result(init_state)
            if result[1] is None:
                self.solver_failed = True
                self.display_hint = False
                self.hide_hint_arrows()
                return
            self.display_hint = True
            self.solvedPath = result[0].path(result[1])
            self.curNode = 0
        except:
            self.solver_failed = True
            self.display_hint = False
            self.hide_hint_arrows()

    def play_solved(self):

        move = self.get_next_move()
        if move[0] == -2:
            self.end_game()
            return

        self.cur_game.move_ball(move[0], move[1])
        self.watch_move(move)
        self.curNode += 1
        next_move = self.get_next_move()
        if next_move[0] != -2:
            self.update_hint_arrows(next_move)
        else:
            self.hide_hint_arrows()

    def watch_move(self, move):

        self.move_num.increase_score()
        ball = self.tubes[move[0]].remove_ball()
        if self.tubes[move[1]].add_ball(ball):
            self.dj.complete_tube()

    # Select/Deselect flasks
    def deselect(self):
        self.tubes[self.selected].select()
        self.selected = -1

    def select(self, tube):
        self.tubes[tube].select()
        self.selected = tube

    # Hint functions
    def update_hint(self):
        init_state = Node(self.cur_game)
        result = solver(init_state, Algorithm.A_STAR, 30)
        if result[1] is None:
            self.hint_available = False
            self.hide_hint_arrows()
            return
        path = result[0].path(result[1])
        if len(path) > 1:
            self.hint_available = True
            hint = self.find_differences(path[1])
            self.update_hint_arrows(hint)

    def update_hint_arrows(self, hint):
        self.hint_up.sprite.rect.left = self.tubes[hint[0]].coords[0] + 5
        self.hint_up.sprite.rect.top = self.tubes[hint[0]].coords[1] - 130
        self.hint_down.sprite.rect.left = self.tubes[hint[1]].coords[0] + 5
        self.hint_down.sprite.rect.top = self.tubes[hint[1]].coords[1] - 130

    def hide_hint_arrows(self):
        self.hint_up.sprite.rect.left = 8000
        self.hint_up.sprite.rect.top = 8000

        self.hint_down.sprite.rect.left = 8000
        self.hint_down.sprite.rect.top = 8000

    def find_differences(self, node):
        tube_from = -1
        tube_to = -1
        game1 = self.cur_game
        game2 = node.gamestate

        for i in range(0, len(game2.tubes)):
            if len(game1.tubes[i].balls) > len(game2.tubes[i].balls):
                tube_from = i
            elif len(game1.tubes[i].balls) < len(game2.tubes[i].balls):
                tube_to = i

            if (tube_from != -1 and tube_to != -1):
                return [tube_from, tube_to]
        return [tube_from, tube_to]

    def get_next_move(self):
        if (self.curNode == len(self.solvedPath) - 1):
            return [-2, -2]
        node1 = self.solvedPath[self.curNode]
        node2 = self.solvedPath[self.curNode + 1]
        tube_from = -1
        tube_to = -1
        game1 = node1.gamestate
        game2 = node2.gamestate
        for i in range(0, len(game2.tubes)):
            if len(game1.tubes[i].balls) > len(game2.tubes[i].balls):
                tube_from = i
            elif len(game1.tubes[i].balls) < len(game2.tubes[i].balls):
                tube_to = i

            if (tube_from != -1 and tube_to != -1):
                return [tube_from, tube_to]
        return [tube_from, tube_to]
class Director:
    """A code template for a person who directs the game. The responsibility of
    this class of objects is to control the sequence of play.

    Stereotype:
        Controller

    Attributes:
        keep_playing (boolean): Whether or not the game can continue.
        board (Board): An instance of the class of objects known as Board.
        console (Console): An instance of the Console class of objects.
        helper (Helper): An instance of the class of objects known as Helper.
        move (Move): An instance of the class of objects known as Move.
        player (Player): An instance of the class of objects known as Player.
        roster (Roster): An instance of the class of objects known as Roster.
    """
    def __init__(self):
        """The class constructor.

        Args:
            self (Director): an instance of Director.
        """
        self.__stop_round = False
        self._board = Board()
        self._console = Console()

    def run_game(self):
        """Starts the game loop to control the sequence of play.

        Args:
            self (Director): an instance of Director.
        """
        while not self._console.ask_stop_game():
            players = self._console.menu()
            if not self._console.ask_stop_game():
                self.__play_round(players)
            print("\n" * 15)

        self._console.clear_screen()

    def __play_round(self, players=list):
        """Runs a round of play and returns a winner.

        Args:
            self (Director): an instance of Director.
            players (list): a list of player names.
        """
        code = self._board.generate_code()
        self._player = Player(players)
        self._score = Score(players)
        self.__stop_round = False

        while not self.__stop_round:
            for player in players:
                if len(players) > 1:
                    self._console.confirm_start(player)

                history = self._player.get_moves(player)
                stats = self._score.get_stats(player)

                guess, elapsed = self._console.play_turn(
                    player, code, history, stats)
                self._score.record_turn(elapsed, player)

                while not self._board.validate_guess(guess):
                    stats = self._score.get_stats(player)
                    guess, elapsed = self._console.play_turn(player,
                                                             code,
                                                             history,
                                                             stats,
                                                             redo=True)
                    self._score.record_turn(elapsed, player)

                if guess == code:
                    stats = self._score.get_stats(player)
                    self._score.update_board(player, stats)

                    self.__end_round(player, stats)
                    self.__stop_round = True
                    self._console.restart_menu()
                    break

                hint = self._board.create_hint(code, guess)
                self._console.show_hint(hint)

                move_hint = (guess, hint)
                self._player.record_move(player, move_hint)

    def __end_round(self, winner=str, stats=tuple):
        """Announces the winner and ends the round

        Args:
            self (Director): an instance of Director.
            winner (list): name of the victor.
            stats (tuple): Tuple of total round points and playtime of player.
        """
        self._console.clear_screen()
        points, time = stats
        print("\n" * 15)
        self._console.cool_print(f'           {winner} wins!')
        print()
        self._console.cool_print(f'   Points: {points} out of 15')
        self._console.cool_print(f'     Time: {time:.2f} seconds')
        input()
Exemple #24
0
def main_game(genomes, config):
  gameSpeed = 5
  gameOver = False

  nets = []
  genomes_track = []
  snakes = []

  for _, genome in genomes:
    net = neat.nn.FeedForwardNetwork.create(genome, config)
    nets.append(net)
    snake_initial_coord = unique_coords(snakes)
    snakes.append(Snake(snake_initial_coord, gameSpeed))
    genome.fitness = 0
    genomes_track.append(genome)

  #snake = Snake((int(BOARD_ROWS / 2), int(BOARD_COLS / 2)), gameSpeed)
  tile_coord = unique_coords(snakes)
  tile = Tile(tile_coord)
  board = Board(screen)
  score = Score(screen)
  
  #last_obstacle = pygame.sprite.Group()

  while not gameOver:

    for event in pygame.event.get():
      if event.type == QUIT:
        gameOver = True
        quit() 

      if event.type == KEYDOWN:
        if event.key == K_UP:
          for snake in snakes:
            snake.move_up()
        if event.key == K_DOWN:
          for snake in snakes:
            snake.move_down()
        if event.key == K_RIGHT:
          for snake in snakes:
            snake.move_right()
        if event.key == K_LEFT:
          for snake in snakes:
            snake.move_left()

    for snake in snakes:
      snake.update()

    check_collide(snakes, tile, genomes_track, nets)

    if tile.is_dead():
      score.update()
      #snake.eat_tile()
      tile_coord = unique_coords(snakes)
      tile = Tile(tile_coord)

    if len(snakes) == 0:
      gameOver = True
      quit() 

    board.clean_board()

    for snake in snakes:
      board.display_snake(snake.get_body())

    board.display_tile(tile.get_coord())

    update_fitness(snakes, tile, genomes_track, nets)

    if pygame.display.get_surface() != None:
      screen.fill(BG_COLOR)
      board.draw()
      score.draw()
      pygame.display.update()

    clock.tick(FPS)
Exemple #25
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller

    Attributes:
        input_service (InputService): The input mechanism.
        keep_playing (boolean): Whether or not the game can continue.
        output_service (OutputService): The output mechanism.
        score (Score): The current score.
        userinput (UserInput): The users input.
        timer (Timer): The remaining time left.
    """
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """

        self.words = []
        for x in range(5):  #Generates 5 word actors
            newWord = Word()
            self.words.append(newWord)

        self._input_service = input_service
        self._keep_playing = True
        self._output_service = output_service
        self._score = Score()
        self._userinput = UserInput()
        self._timer = Timer()

    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()
            sleep(constants.FRAME_LENGTH)

    def _get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means checking the letters the user types.

        Args:
            self (Director): An instance of Director.
        """
        self.input_letter = self._input_service.get_letter()

    def _do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means checking the words for correctness and subtracting
        time.

        Args:
            self (Director): An instance of Director.
        """

        self._move_words()
        self._handle_letter_input()
        self._check_words()
        self._timer.subtract_time()
        self._timer.check_time()

    def _do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means drawing everything to the screen.

        Args:
            self (Director): An instance of Director.
        """
        self._output_service.clear_screen()
        self._output_service.draw_actors(self.words)
        self._output_service.draw_actor(self._timer)
        self._output_service.draw_actor(self._userinput)
        self._output_service.draw_actor(self._score)
        self._output_service.flush_buffer()

    def _check_words(self):
        """Handles the checking of words as they are typed.

        Args:
            self (Director): An instance of Director.
        """

        for x in range(5):

            if self._userinput.check_word == self.words[x]._word:
                self._score.add_points(self.words[x]._points)
                self.words[x].reset()
                self._userinput._clear_letters()

    def _move_words(self):
        """Handles moving the words around the screen.

        Args:
            self (Director): An instance of Director.
        """

        for x in range(len(self.words)):
            self.words[x].move_next()

    def _handle_letter_input(self):
        """Handles adding letters to an array as they are typed.

        Args:
            self (Director): An instance of Director.
        """

        if self.input_letter == "":
            pass
        elif self.input_letter == "*":
            self._userinput._clear_letters()
        else:
            self._userinput._add_letter(self.input_letter)
Exemple #26
0
def play(category):
	""" Play the blindtest itself, save and show score and ask a rating for the project."""

	# Get Category
	try:
		category = Category.get(id=category)
	except Exception:
		print("Impossible de récupérer la catégorie dans la base de données.")

	# Execute rest of code only if category exists
	if category is not None:
		# Convert musics from this category to a list
		musics = list(category.musics)
		# Generate a shuffled list
		shuffled_musics = list(musics)
		shuffle(shuffled_musics)

		# Initialize score
		points = 0

		# Generate a string with the non-shuffled list of musics
		musics_list = ""
		for music in musics:
			musics_list = musics_list + ("\n\t%i %s" % (reduce_id(music.id), music.name))

		# Play musics one by one and ask user what music is it
		for i, music in enumerate(shuffled_musics):
			# Define the right answer
			answer = reduce_id(music.id)
			# Initialize user_input
			user_input = None

			# Show answers list
			print("Propositions :%s\n" % musics_list)

			# Play music
			music_to_play = Music(music)

			# Execute code only if the music exists
			if music_to_play is not None:
				if music_to_play.is_exists():
					music_to_play.play()

				# Ask user for the answer
				while user_input is None:
					user_input = input("Votre réponse : ")
					try:
						user_input = int(user_input)
					except ValueError:
						print(settings.errors['NOT_A_NUMBER'])

					if user_input in range(1, 11):
						if user_input == answer:
							print("Votre réponse était JUSTE.")
							points = points + 1
						else:
							print("Votre réponse était FAUSSE.")
					else:
						user_input = None
						print("Veuillez entrer un nombre entre 1 et 10.")

		# Save and show score
		score = Score(points)
		score.save()
		score.show()

		# Ask for a rating
		thanks()

		# Go back to main menu
		menus.main()
Exemple #27
0
def play(category):
    """ Play the blindtest itself, save and show score and ask a rating for the project."""

    # Get Category
    try:
        category = Category.get(id=category)
    except Exception:
        print("Impossible de récupérer la catégorie dans la base de données.")

    # Execute rest of code only if category exists
    if category is not None:
        # Convert musics from this category to a list
        musics = list(category.musics)
        # Generate a shuffled list
        shuffled_musics = list(musics)
        shuffle(shuffled_musics)

        # Initialize score
        points = 0

        # Generate a string with the non-shuffled list of musics
        musics_list = ""
        for music in musics:
            musics_list = musics_list + ("\n\t%i %s" %
                                         (reduce_id(music.id), music.name))

        # Play musics one by one and ask user what music is it
        for i, music in enumerate(shuffled_musics):
            # Define the right answer
            answer = reduce_id(music.id)
            # Initialize user_input
            user_input = None

            # Show answers list
            print("Propositions :%s\n" % musics_list)

            # Play music
            music_to_play = Music(music)

            # Execute code only if the music exists
            if music_to_play is not None:
                if music_to_play.is_exists():
                    music_to_play.play()

                # Ask user for the answer
                while user_input is None:
                    user_input = input("Votre réponse : ")
                    try:
                        user_input = int(user_input)
                    except ValueError:
                        print(settings.errors['NOT_A_NUMBER'])

                    if user_input in range(1, 11):
                        if user_input == answer:
                            print("Votre réponse était JUSTE.")
                            points = points + 1
                        else:
                            print("Votre réponse était FAUSSE.")
                    else:
                        user_input = None
                        print("Veuillez entrer un nombre entre 1 et 10.")

        # Save and show score
        score = Score(points)
        score.save()
        score.show()

        # Ask for a rating
        thanks()

        # Go back to main menu
        menus.main()
Exemple #28
0
class Arena(object):
    database = None
    event_settings = None
    displays = None
    match_aborted = False
    last_ds_packet_time = 0
    blue_realtime_score = 0
    red_realtime_score = 0
    alliance_stations = {}
    tba_client = None
    match_start_time = 0
    last_match_time_sec = 0
    match_time_sec = 0

    red_score = Score()
    blue_score = Score()

    current_sound = None

    driverstation_listener = None
    driverstation_udp_packet_listener = None

    ## Arena constructor
    # @param db_path Filepath to the database file
    # @param ws_server Websocket server object
    def __init__(self, db_path, ws_server):
        self.database = Database(db_path)
        self.ws = ws_server

        # Set up alliance stations
        self.alliance_stations["R1"] = AllianceStation()
        self.alliance_stations["R2"] = AllianceStation()
        self.alliance_stations["R3"] = AllianceStation()
        self.alliance_stations["B1"] = AllianceStation()
        self.alliance_stations["B2"] = AllianceStation()
        self.alliance_stations["B3"] = AllianceStation()

        self.match_state = MatchState.pre_match

        self.last_match_time = 0
        self.last_match_state = -1

        self.audience_display_mode = "blank"
        self.alliance_station_display_mode = "match"

    ## Function that starts the field
    def Run(self):
        # listen for driverstations
        self.driverstation_listener = Thread(target=ListenForDriverstations,
                                             args=(self, None))
        self.driverstation_listener.start()

        # Listen for DS UDP packets
        self.driverstation_udp_packet_listener = Thread(
            target=ListenForDsUdpPackets, args=(self, None))
        self.driverstation_udp_packet_listener.start()

        notice("Arena has started")
        while True:
            self.Update()
            time.sleep(arena_loop_period_ms / 1000)

    ## Function for retreving the assigned station of a specified team
    # @param team_id Team number
    # @return Station id for team
    def GetAssignedAllianceStation(self, team_id: int):
        for station in self.alliance_stations:
            if self.alliance_stations[station].team != None and str(
                    self.alliance_stations[station].team.id) == str(team_id):
                return station
        return ""

    ## Manages game states and robot connections
    def Update(self):
        # print("updating")
        auto = False
        enabled = False
        send_ds_packet = False
        match_time_sec = self.MatchTimeSec()

        if self.match_state == MatchState.pre_match:
            auto = True
            enabled = False

        elif self.match_state == MatchState.start_match:
            self.match_start_time = time.time()
            self.last_match_time_sec = -1
            auto = True
            self.audience_display_mode = "match"
            self.alliance_station_display_mode = "match"
            # TODO: notify display modes
            self.match_state = MatchState.auto_period
            enabled = True
            send_ds_packet = True
            self.current_sound = "auto"

        elif self.match_state == MatchState.auto_period:
            auto = True
            enabled = True
            if match_time_sec >= matchtiming.auto_duration_sec:
                auto = False
                send_ds_packet = True
                self.match_state = MatchState.teleop_period
                enabled = True
                self.current_sound = "teleop"

        elif self.match_state == MatchState.teleop_period:
            auto = False
            enabled = True
            if match_time_sec >= matchtiming.auto_duration_sec + matchtiming.teleop_duration_sec:
                self.match_state = MatchState.pre_match
                auto = False
                enabled = False
                send_ds_packet = True
                self.current_sound = "matchend"
                NotifyAll(self.ws, self)
                time.sleep(3)
                self.audience_display_mode = "blank"
                self.alliance_station_display_mode = "logo"

        NotifyAll(self.ws, self)

        self.last_match_time = match_time_sec
        self.last_match_state = self.match_state

        if send_ds_packet or (timeMS() -
                              self.last_ds_packet_time) >= ds_packet_period_ms:
            self.SendDsPacket(auto, enabled)

    ## Get the time to be displayed on the match timer
    # @return Match time
    def MatchTimeSec(self):
        if self.match_state == MatchState.pre_match or self.match_state == MatchState.start_match:
            return 0
        return (time.time() - self.match_start_time)  #+ 130

    def SendDsPacket(self, auto: bool, enabled: bool):
        for station in self.alliance_stations:
            station = self.alliance_stations[station]

            dsconn = station.driverstation_connection
            if dsconn != None:
                dsconn.auto = auto
                dsconn.enabled = enabled and not station.estop and not station.bypass
                dsconn.estop = station.estop
                dsconn.Update(self)
        self.last_ds_packet_time = timeMS()

    def CheckCanStartMatch(self):
        if self.match_state != MatchState.pre_match:
            return "Cannot start match while there is a match in progress or with results still pending"

    def AssignTeam(self, team_id: int, station: str):
        team_id = int(team_id)
        if station not in self.alliance_stations:
            return "Invalid alliance station"

        dsconn = self.alliance_stations[station].driverstation_connection

        if dsconn != None and dsconn.team_id == team_id:
            return None

        if dsconn != None:
            dsconn.Close()
            self.alliance_stations[station].team = None
            self.alliance_stations[station].driverstation_connection = None

        if team_id == 0:
            self.alliance_stations[station].team = None
            return None

        team = Team()
        team.id = team_id
        self.alliance_stations[station].team = team

        notice(f"Team {team_id} has been assigned to station {station}")
        return None

    def ResetMatch(self):
        if self.match_state != MatchState.pre_match:
            return "Cannot reset a match while it is in progress"

        self.match_state = MatchState.pre_match
        self.match_aborted = False
        self.alliance_stations["R1"].bypass = False
        self.alliance_stations["R2"].bypass = False
        self.alliance_stations["R3"].bypass = False
        self.alliance_stations["B1"].bypass = False
        self.alliance_stations["B2"].bypass = False
        self.alliance_stations["B3"].bypass = False

    def AbortMatch(self):
        if self.match_state == MatchState.pre_match:
            return "Cannot abort a match that is not running"

        self.match_state = MatchState.pre_match
        self.match_aborted = True
        self.current_sound = "abort"
        warn("Match aborted")

    def StartMatch(self):
        for station in self.alliance_stations:
            station = self.alliance_stations[station]

            if station.driverstation_connection != None:
                dsconn = station.driverstation_connection
                SignalMatchStart(dsconn)

                if station.team != None and not station.team.has_connected and dsconn.robot_linked:
                    station.team.has_connected = True

        self.match_state = MatchState.start_match
        notice("Match has been started")
Exemple #29
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to control the sequence of play.
    
    Stereotype:
        Controller


    """
    def __init__(self, input_service, output_service):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self._input_service = input_service
        self._output_service = output_service
        self._buffer = Buffer()
        self._word = Word('test')
        self._current_words = []
        self._text_words = []
        self._inputted_letter = ''
        self._score = Score()

        self._keep_playing = True

    def start_game(self):
        """
            Begins the game cycle
        """
        self.setup_game()
        while self._keep_playing:
            self._get_inputs()
            self._do_updates()
            self._do_outputs()
            sleep(constants.FRAME_LENGTH)

    def _get_random_word(self):
        """
        This function retrieves a random word from the txt file.
        """
        words = open('speed\game\words.txt').read().splitlines()

        return random.choice(words)

    def _make_words(self):
        """
        This function makes word actors with random words pulled from the txt file.
        """

        for i in range(random.randint(1, 2)):
            word = Word(self._get_random_word())
            self._current_words.append(word)
            self._text_words.append(word.get_text())

    def move_word_list(self, actor_list):
        """
        This function takes the list of word actors and moves them all according to their velocity. 
        """
        for actor in actor_list:
            actor.move_next()

    def setup_game(self):
        """
        Resets the buffer so that it displays correctly at the beginning
        """
        self._buffer.reset_buffer()

    def _get_inputs(self):
        """
        Gets the keystrokes of the player
        """

        self._inputted_letter = self._input_service.get_letter()

    def _do_updates(self):
        """
        With the keystrokes, this function writes the letters to the buffer,
        checks if the keystrokes match the moving word actors, and moves the
        actors continuely. 
        """
        if self._inputted_letter:
            if self._inputted_letter == '*':
                self._buffer.reset_buffer()

            else:
                self._buffer.set_letter(self._inputted_letter)

        if self._buffer.get_text_buffer() != '':
            buffer = self._buffer.get_text_buffer()
            if 'bombz' in buffer:
                self._score.set_score(random.randint(1000, 10000))
                self._score.set_text(f'Score : {self._score.get_score()}')
                self._text_words.clear()
                self._current_words.clear()
            self._text_words
            for i in self._text_words:
                if i in buffer:
                    self._score.set_word_points(i)

                    index = self._text_words.index(i)

                    del self._text_words[index]
                    del self._current_words[index]
                    break

        self.move_word_list(self._current_words)

    def _do_outputs(self):
        """
        This function refreshes the asciimatics screen, and adds more words to the screen 
        if there are less than 15 currently being displayed. It also draws all of the game
        components to the screen. 
        """
        self._output_service.clear_screen()

        test = len(self._current_words)
        if len(self._current_words) < 15:

            self._make_words()

        self._output_service.draw_actor(self._score)
        self._output_service.draw_actors(self._current_words)
        self._output_service.draw_actor(self._buffer)

        self._output_service.flush_buffer()
Exemple #30
0
def main_game(genomes, config):
  gameSpeed = 4
  gameOver = False
  gameQuit = False

  ground = Ground(screen, -1 * gameSpeed)
  score = Score(screen)

  nets = []
  genomes_track = []
  trexs = []

  for _, genome in genomes:
    net = neat.nn.FeedForwardNetwork.create(genome, config)
    nets.append(net)
    trexs.append(TRex(screen, 44, 47))
    genome.fitness = 0
    genomes_track.append(genome)


  clouds = pygame.sprite.Group()
  cactus = pygame.sprite.Group()
  pteros = pygame.sprite.Group()
  last_obstacle = pygame.sprite.Group()

  Cloud.containers = clouds
  Cactus.containers = cactus
  Ptero.containers = pteros

  while not gameOver:
    for event in pygame.event.get():
      if event.type == QUIT:
        gameOver = True
        quit() 
        
      if event.type == KEYDOWN:
        if event.key == K_SPACE or event.key == K_UP:
          for trex in trexs:
            trex.jump()
        if event.key == K_DOWN:
          for trex in trexs:
            trex.duck()

      if event.type == KEYUP:
        for trex in trexs:
          trex.no_duck()

    
    check_cactus_collide(cactus, trexs, genomes_track, nets)
    check_pteros_collide(pteros, trexs, genomes_track, nets)

    create_cactus(cactus, last_obstacle, gameSpeed)
    create_ptero(pteros, last_obstacle, gameSpeed)
    create_clouds(clouds)

    for trex in trexs:
      trex.update()
    
    update_fitness(trexs, cactus, pteros, genomes_track, nets)

    ground.update()
    clouds.update()
    cactus.update()
    pteros.update()
    score.update()

    if pygame.display.get_surface() != None:
      screen.fill(BG_COLOR)
      ground.draw()
      clouds.draw(screen)
      cactus.draw(screen)
      pteros.draw(screen)
      score.draw()

      for trex in trexs:
        trex.draw()

      pygame.display.update()

    if (score.get_score() > 1000 and gameSpeed == 4) or \
      (score.get_score() > 2000 and gameSpeed == 4.5) or \
      (score.get_score() > 3000 and gameSpeed == 5) or \
      (score.get_score() > 4000 and gameSpeed == 5.5):
      gameSpeed += 0.5
      ground.set_speed(-1 * gameSpeed)
    
    if len(trexs) == 0:
      gameOver = True

    clock.tick(FPS)

  """
Exemple #31
0
class Game:
    def __init__(self):
        init()
        font.init()
        display.set_caption(TITLE)
        key.set_repeat()

        self.playing = False

        self.screen = display.set_mode((WIDTH, HEIGHT))

        self.clock = time.Clock()
        self.dt = self.clock.tick(FPS) / 1000

        self.labels = list()
        self.infos = list()

        self.all_sprites = Group()

        self.adventure = Home(self)

        self.camera = Camera(self.adventure.map.width, self.adventure.map.height)
        self.score = Score("Renato")

        self.game_over = False

    def update_adventure(self, adventure):
        self.show_ended_screen()

        self.adventure.player.kill()
        self.labels = list()
        self.infos = list()

        self.adventure = adventure
        self._update_camera()

        self.show_go_screen()

        self.score.start_adventure(adventure.level.level_score)

    def run(self):
        self.playing = True

        while self.playing:
            self.events()
            self.update()
            self.draw()

            if self.game_over:
                break

            if self.adventure.finish:
                self.show_end_adventure_screen()
                break

    def update(self):
        # update info
        self.infos = list()

        self.adventure.update()
        self.all_sprites.update()

        self.camera.update(self.adventure.player)

    def draw(self):
        if not self.adventure.has_menu:
            self.screen.blit(self.adventure.map_image, self.camera.apply_rect(self.adventure.map_rect))

            for sprite in self.all_sprites:
                self.screen.blit(sprite.image, self.camera.apply(sprite))

            for label in self.labels:
                self.screen.blit(label.surface, self.camera.apply_rect(label.rect))

            for info in self.infos:
                self.screen.blit(info.surface, info.rect)

            for zombie in self.adventure.zombies:
                zombie.draw_health()

        display.flip()

    def events(self):
        events = key_event.get()
        if not self.adventure.has_menu:
            for event in events:
                if event.type == QUIT:
                    self.__quit__()
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        self.__quit__()

        self.adventure.events(events)

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        self.update()

        start_display = Surface((WIDTH, HEIGHT), SRCALPHA)
        for alpha in range(255, 0, -1):
            start_display.fill((0, 0, 0, alpha))

            self.screen.blit(self.adventure.map_image, self.camera.apply_rect(self.adventure.map_rect))
            self.screen.blit(start_display, (0, 0))

            display.flip()
            time.delay(10)

    def show_ended_screen(self):
        self.update()

        start_display = Surface((WIDTH, HEIGHT), SRCALPHA)
        for alpha in range(255):
            start_display.fill((0, 0, 0, alpha))

            self.screen.blit(self.adventure.map_image, self.camera.apply_rect(self.adventure.map_rect))
            self.screen.blit(start_display, (0, 0))

            display.flip()
            time.delay(10)

    def show_game_over_screen(self):
        game_over_display = Surface((WIDTH, HEIGHT), SRCALPHA)
        game_over_text = Label('Game Over', 'assets/fonts/blocks.ttf', 20, (HEIGHT / 2) - 100, font_size=72)
        score_text = Label('For save the score you need finish adventure', 'assets/fonts/future_narrow.ttf', 20,
                           (HEIGHT / 2) - 120, font_size=24)

        return_text = Label('You will return to home', 'assets/fonts/future_narrow.ttf', 20, (HEIGHT / 2) - 160,
                            font_size=24)
        for alpha in range(255):
            game_over_display.fill((0, 0, 0, alpha))

            self.screen.blit(game_over_display, (0, 0))

            self.screen.blit(game_over_text.surface, game_over_text.rect)
            self.screen.blit(score_text.surface, score_text.rect)
            self.screen.blit(return_text.surface, return_text.rect)

            display.flip()

            time.delay(10)

    def show_end_adventure_screen(self):
        end_surface = Surface((WIDTH, HEIGHT), SRCALPHA)
        end_text = Label('Good Nice!', 'assets/fonts/blocks.ttf', 20, (HEIGHT / 2) - 100, font_size=72)
        score_text = Label(f'Score: {self.score.calculate_score()}', 'assets/fonts/future_narrow.ttf', 20,
                           (HEIGHT / 2) - 120, font_size=24)

        return_text = Label('You will return to home and see you score ranking', 'assets/fonts/future_narrow.ttf', 20,
                            (HEIGHT / 2) - 160,
                            font_size=24)
        for alpha in range(255):
            end_surface.fill((0, 0, 0, alpha))

            self.screen.blit(end_surface, (0, 0))

            self.screen.blit(end_text.surface, end_text.rect)
            self.screen.blit(score_text.surface, score_text.rect)
            self.screen.blit(return_text.surface, return_text.rect)

            display.flip()

            time.delay(10)

    def _update_camera(self):
        self.camera = Camera(self.adventure.map.width, self.adventure.map.height)

    @staticmethod
    def __quit__():
        quit()
        sys.exit()