示例#1
0
class Revisao:
    """Calsse que executa o programa criado na aula de revisão."""

    def setup(self, width, height, bg=color.BLACK):
        self.window = Window(width, height)
        self.objects = []
        self.background = bg

    def add_object(self, object):
        self.objects.append(object)

    def run(self):
        clock = pygame.time.Clock()
        running = True
        while running:
            # handle events
            for evt in pygame.event.get():
                if evt.type == pygame.QUIT:
                    running = False
                    continue
            # update objects
            for obj in self.objects:
                obj.update(self.window.size)
            # clear window.
            self.window.clear(self.background)
            # draw objects
            for obj in self.objects:
                self.window.draw(obj)
            # update window
            self.window.update()
            # ensure maximum speed
            clock.tick(240)
示例#2
0
def main(screen):

   # setup the basic syntax for text files
   text_syntax = SyntaxClass("basic")
   text_syntax.add("character", r".")
   text_syntax.add("word", r" ")
   text_syntax.add("sentance", r"\.")

   # make the main window 
   mainwin = Window(screen, FileBuffer(open("README.markdown")))
   mainwin.render()

   # the event loop
   while True: 
      event = screen.getch()
      if event == ord("q"): break 
      
      if event == ord("e"): mainwin.clear()
      if event == ord("r"): mainwin.render()
      if event == ord("f"): mainwin.addstr("X")
      if event == ord("w"): mainwin.rmove(0, -1)
      if event == ord("a"): mainwin.rmove(-1, 0)
      if event == ord("s"): mainwin.rmove(0, +1)
      if event == ord("d"): mainwin.rmove(+1, 0)
      if event == ord("x"): mainwin.here()

      
      def find(syntaxname):
         return lambda t, x, y: text_syntax.find(syntaxname, t, x, y)

      if event == ord("c"): mainwin.movef(find("character"))
      if event == ord("v"): mainwin.movef(find("word"))
示例#3
0
class Game:
    def __init__(self):
        self.window_width = 640
        self.window_height = 480
        self.window = Window("WORMS BITCH", self.window_width, self.window_height)
        self.event = Event()
        self.main_scene = MainScene(self)

        self.clock = pygame.time.Clock()
        self.delta = 0
        self.end = False # Set this attribute to True ton end the game.


    def update(self):
        self.update_delta()
        self.event.update()

        if self.event.exit:
            self.end = True

        self.main_scene.update(self.event)


    def draw(self):
        self.window.clear()
        self.main_scene.draw()
        self.window.update()

    def update_delta(self):
        self.delta = self.clock.tick(60)
        

    def exit(self):
        pass
示例#4
0
class GlutWindow(object):
    def __init__(self, width, height, title):
        super(GlutWindow, self).__init__()
        self.width = width
        self.height = height
        self.title = title

        self.texture_id = 0
        self.vertices = None

        self.pixels = np.zeros(self.width * self.height)
        self.window = Window(self.width, self.height, self.pixels)

        self.setup()

    def mouse_event(self, button, state, x, y):
        self.window.mouse_event(button, state, x, y)

    def key_event(self, key, key_is_down, x, y):
        key = ord(key)
        self.window.key_event(key, key_is_down)

    def key_down(self, key, x, y):
        self.key_event(key, True, x, y)

    def key_up(self, key, x, y):
        self.key_event(key, False, x, y)

    def setup(self):
        self.setup_glut()
        self.setup_gl()

    def setup_glut(self):
        # glutInit(sys.argv)
        glutInit()
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
        glutInitWindowSize(self.width, self.height)

        glutCreateWindow(self.title)
        glutDisplayFunc(self.show)

        glutMouseFunc(self.mouse_event)

        glutKeyboardFunc(self.key_down)
        glutKeyboardUpFunc(self.key_up)
        # glutSetKeyRepeat(GLUT_KEY_REPEAT_ON)

    def setup_gl(self):
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glClearColor(0, 0, 0, 1)
        glViewport(0, 0, self.width, self.height)

        self.texture_id = glGenTextures(1)
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.texture_id)
        # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
        # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height,
                     0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, self.pixels)

        self.vertices = [
            # (u, v), (x, y, z)
            (0, 0), (-1, -1, 0),
            (1, 0), (1, -1, 0),
            (1, 1), (1, 1, 0),
            (0, 1), (-1, 1, 0),
        ]

    def update(self, dt=100):
        # clear
        self.clear()

        # update
        delta = dt / 1000.0
        self.window.update(delta)

        # draw
        self.window.draw()

        # show
        glutPostRedisplay()
        glutTimerFunc(dt, self.update, dt)

    def run(self):
        self.update()
        glutMainLoop()

    def clear(self):
        glClear(GL_COLOR_BUFFER_BIT)
        self.window.clear()

    def show(self):
        # update texture and render
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, self.width, self.height,
                        GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, self.pixels)

        vertices = self.vertices
        glBegin(GL_QUADS)
        for i in range(0, 4 * 2, 2):
            glTexCoord2f(*vertices[i])
            glVertex3f(*vertices[i + 1])
        glEnd()

        glutSwapBuffers()
示例#5
0
class SnakeGame:
    """
    A simple structure for a Snake-like game.

    Attributes:
    -----------------
        window : Window
            The main window of the game.
            Makes sure that the implementation is visible to the user.

        snake_size : tuple(int, int)
            The size of the snake.

        snake : Snake
            The controllable snake.

        current_movement : Callable
            One of the four directional functions from the Snake class.
            Saved for convenience and used to call movement on the snake-attribute.

        fruit_coordinates : list(int, int)
            The positional coordinates of the fruit that the snake is to eat.

        fruit_size : tuple(int, int)
            The size of the fruit.

        running : bool
            Used to control the state of the game.
            If false, the player has either exited or lost the game.

        last_update_time : int
            If the difference between this and a clock check is above 150
            the method update_movement is called and this attribute
            updated.

    Methods:
    -----------------
        handle_keydown(event):
            Function to handle user input events incoming from the underlying pygame module.

        draw():
            Draw the game to the screen.

        move_fruit():
            Randomly moves the fruit until it does not collide with the snake anymore.
            Used after the fruit is picked up.

        fruit_pickup():
            Used to control if the snake is able to pick up the fruit.
            If the snake is able to pick the fruit up, the snake will grow
            and the fruit will be moved to a new position.

        check_if_inside_window():
            Used to control whether the snake is inside the boundaries of
            the screen or not. If the snake is not inside the boundaries,
            the game is over.

        run_game_logic():
            The main function used to run the game logic.
            Makes sure that all other functions are called as they should.

        game_loop():
            The entry point of the game.
            Clears the screen, runs the game logic, and make sure that the
            screen is presented at the end.

        update_move():
        Function to update the movement and control if the
        snake collides with itself.
    """
    #pylint: disable=no-member

    def __init__(self, background_colour, width, height):
        """Initialize the game. The parameters are passed on to the init function of Window


        Parameters:
        ------------------------------------------
        colour : list(int, int, int)
            A triple of values between 0 and 255 indicating the r, g, b value of the rectangle

        top_left : tuple(int, int)
            The x- and y-coordinates for the top left corner of the rectangle

        size : tuple(int, int)
            The width and height of the rectangle
        """
        self.window = Window(background_colour, width, height)
        self.snake_size = (30, 30)
        self.snake = Snake((width//2, height//2), self.snake_size, (75, 75, 75))
        self.current_movement = Snake.move_up
        self.fruit_coordinates = (0, 0)
        self.fruit_size = (30, 30)
        self.running = True
        self.last_update_time = pygame.time.get_ticks()

    def handle_keydown(self, event):
        """Handle key input from the user.

        Check if the key pressed is any of the keys used to control the snake,
        that is any of the WASD-keys or the arrow keys, or ESC for quiting the game.

        If any of the WASD-keys or arrow keys are pressed, change direction of the snake
        to the appropiate direction.

        Parameters:
            event : pygame.event
                An event containing a pressed key.
        """

        pressed_key = event.key

        if pressed_key in (pygame.K_a, pygame.K_LEFT):
            self.current_movement = Snake.move_left
        elif pressed_key in (pygame.K_d, pygame.K_RIGHT):
            self.current_movement = Snake.move_right
        elif pressed_key in (pygame.K_w, pygame.K_UP):
            self.current_movement = Snake.move_up
        elif pressed_key in (pygame.K_s, pygame.K_DOWN):
            self.current_movement = Snake.move_down
        elif pressed_key == pygame.K_ESCAPE:
            self.running = False

    def draw(self):
        """Makes sure all the components of the game are presented on the screen."""
        self.window.draw_rect(
            (255, 0, 0),
            self.fruit_coordinates,
            self.fruit_size
        )

        for part in self.snake:
            coordinates = part.get_coordinates()
            size = part.get_size()
            colour = part.get_colour()
            self.window.draw_rect(
                colour,
                coordinates,
                size
            )

    def move_fruit(self):
        """
        Randomly moves the fruit until it does not collide with the snake anymore.
        Used after the fruit is picked up.
        """
        while True:
            screen_size = (self.window.width(), self.window.height())
            new_x = randrange(0, screen_size[0] - self.fruit_size[0], self.fruit_size[0])
            new_y = randrange(0, screen_size[1] - self.fruit_size[1], self.fruit_size[1])
            self.fruit_coordinates = (new_x, new_y)

            position_ok = True

            if self.snake.check_collision(self.fruit_coordinates, self.fruit_size):
                position_ok = False

            if position_ok:
                break

    def fruit_pickup(self):
        """
        Used to control if the snake is able to pick up the fruit.
        If the snake is able to pick the fruit up, the snake will grow
        and the fruit will be moved to a new position.
        """
        if self.snake.check_collision_with_fruit(self.fruit_coordinates, self.fruit_size):
            self.move_fruit()
            self.snake.grow()

    def is_inside_window(self):
        """
        Used to control whether the snake is inside the boundaries of
        the screen or not. If the snake is not inside the boundaries,
        the game is over.

        Return: bool
            True: Inside window
            False: Not inside window
        """
        screen_size = (self.window.width(), self.window.height())
        
        if self.snake.inside_bounds(
                (0, 0),
                (screen_size[0] - self.snake_size[0],
                 screen_size[1] - self.snake_size[1])):

            return True
        return False

    def update_move(self):
        """
        Function to update the movement and control if the
        snake collides with itself.

        Called through a pygame registered event.
        """
        self.current_movement(self.snake)
        if self.snake.check_collision_with_self() or not self.is_inside_window():
            self.running = False

    def run_game_logic(self):
        """
        The entry point of the game.
        Clears the screen, runs the game logic, and make sure that the
        screen is presented at the end.
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            elif event.type == pygame.KEYDOWN:
                self.handle_keydown(event)

        time_since_update = pygame.time.get_ticks() - self.last_update_time

        if time_since_update > 150:
            self.last_update_time = pygame.time.get_ticks()
            self.update_move()

        self.fruit_pickup()

        self.draw()

    def game_loop(self):
        """
        The main loop of the game.

        Will continue to play until running is set to false.
        """
        self.running = True
        while self.running:
            self.window.clear()
            self.run_game_logic()
            pygame.display.flip()
示例#6
0
def start_client(sc, origin, pubkey, subkey, channel):
    global MSG_CURSOR
    global AUTO_PUBLISH

    # Set locale encoding
    import locale
    locale.setlocale(locale.LC_ALL, '')
    code = locale.getpreferredencoding()

    MAXY, MAXX = sc.getmaxyx()

    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_WHITE, COLOR_DEFAULT)
    curses.init_pair(2, curses.COLOR_CYAN, COLOR_DEFAULT)
    curses.init_pair(3, curses.COLOR_YELLOW, COLOR_DEFAULT)
    curses.init_pair(4, curses.COLOR_MAGENTA, COLOR_DEFAULT)

    # Check for min terminal height
    if MAXY < 46:
        sc.addstr(0, 0, "Your terminal window is too small. Please make it taller and try again. Press any key to continue...", curses.color_pair(3))
        sc.getch()
        return 1

    draw_header(sc, origin, pubkey, subkey, channel)

    # Draw winows
    sub_win = Window(sc, HEADER_LINES + 1, SUB_WINDOW_LINES, "Messages:")
    presence_win = Window(sc, HEADER_LINES + SUB_LINES + PUB_LINES + 1, PRESENCE_LINES, "Presence:")
    history_win = Window(sc, HISTORY_Y, HISTORY_LINES, "History:")

    # Draw Subscribe controls
    sc.addstr(SUB_Y, 22, "Scroll", curses.color_pair(1))
    sc.addch(SUB_Y, 29, curses.ACS_UARROW, curses.color_pair(2))
    sc.addch(SUB_Y, 31, curses.ACS_DARROW, curses.color_pair(2))

    # Draw history controls
    sc.addstr(HISTORY_Y, 10, "Refresh", curses.color_pair(1))
    sc.addstr(HISTORY_Y, 18, "(h)", curses.color_pair(2))
    sc.addstr(HISTORY_Y, 22, "Scroll", curses.color_pair(1))
    sc.addstr(HISTORY_Y, 29, "(j)", curses.color_pair(2))
    sc.addstr(HISTORY_Y, 33, "(k)", curses.color_pair(2))

    # Draw publish controls
    sc.addstr(PUB_Y, 0, "Publish:          Re-Publish last", curses.color_pair(1))
    sc.addstr(PUB_Y, 9, "(Ctrl-G)", curses.color_pair(2))
    sc.addstr(PUB_Y, 34, "(r)", curses.color_pair(2))
    auto_publish_state(sc, "info")

    pub_win, pub_text = draw_pubbox(sc)

    # Setup stdscr
    sc.refresh()
    sub_win.refresh()
    pub_win.refresh()
    presence_win.refresh()
    history_win.refresh()

    logger = threading.Thread(target=message_log, args=(sub_win,))
    logger.daemon=True
    logger.start()

    log_parser = threading.Thread(target=parse_logs, args=(sc,))
    log_parser.daemon = True
    log_parser.start()

    subscriber = threading.Thread(target=subscribe, args=(origin, subkey, channel))
    subscriber.daemon = True
    subscriber.start()

    presence_thread = threading.Thread(target=presence, args=(origin, subkey, channel, presence_win))
    presence_thread.daemon = True
    presence_thread.start()

    history(origin, subkey, channel, history_win)

    while True:
        cmd = sc.getch()

        if cmd == ord('q'):
            break

        # Clear windows
        elif cmd == ord('c'):
            sub_win.clear()
            history_win.clear()
            presence_win.clear()

        elif cmd == ord('p'):
            #TODO: redrawing all is overkill
            pub_win, pub_text = draw_pubbox(sc)
            publish(origin, pubkey, subkey, channel, pub_text.edit())

        # Re-publish
        elif cmd == ord('r'):
            publish(origin, pubkey, subkey, channel, pub_text.gather())

        # Subscribe pane scrolling
        elif cmd == curses.KEY_UP:
            sub_win.scroll(-1)
        elif cmd == curses.KEY_DOWN:
            sub_win.scroll(1)

        # Auto publishing
        elif cmd == ord('a'):
            auto_publish_state(sc, "editing")
            sc.refresh()

            text = pub_text.edit()
            loop_timer = LoopTimer(5.0, publish, args=(origin, pubkey, subkey, channel, text))
            loop_timer.start()

            auto_publish_state(sc, "publishing")

            ch = sc.getch()
            loop_timer.cancel()
            loop_timer = None

            auto_publish_state(sc, "info")

        # History controls
        elif cmd == ord('h'):
            history(origin, subkey, channel, history_win)
        elif cmd == ord('j'):
            history_win.scroll(1)
        elif cmd == ord('k'):
            history_win.scroll(-1)

    return 1
示例#7
0
class Game:

    win_width = 1450
    win_height = 800

    def __init__(self):
        self.win = Window((Game.win_width, Game.win_height))
        self.sky = Sky(Game.win_width, Game.win_height)
        self.platform = Platform(Game.win_width, 96, Game.win_height - 96 - 30)
        self.dino = None
        self.enemy_velocity = 250
        self.score = 0
        self.create_handlers()
        self.enemies = []

    def create_handlers(self):
        self.win.add_handler('w', lambda x: self.jump())
        self.win.add_handler('W', lambda x: self.jump())
        self.win.add_handler('<space>', lambda x: self.reset())

    def reset(self):
        if not self.dino.alive:
            self.dino.alive = True
            self.enemies = []
            self.score = 0
            self.enemy_velocity = 250

    def jump(self):
        if self.dino:
            self.dino.jump()

    @property
    def window_is_open(self):
        return self.win.open

    def check_collision_with_ground(self):
        if not (self.dino.y + self.dino.height >= self.platform.y):
            return
        self.dino.y = self.platform.y - self.dino.height
        self.dino.reset_force()
        self.dino.allow_jump()

    def update_dino(self, dt: float):
        if not self.dino:
            return
        self.dino.tick(dt)
        self.check_collision_with_ground()

    def remove_enemies(self):
        for enemy in self.enemies:
            if enemy.x + enemy.width < 0:
                self.enemies.remove(enemy)
            else:
                return

    def move_enemies(self, dt: float):
        delta = -dt * self.enemy_velocity
        for enemy in self.enemies:
            enemy.move(delta)

    def tick_enemies(self, dt: float):
        for enemy in self.enemies:
            enemy.tick(dt)

    def update_enemies(self, dt: float):
        self.move_enemies(dt)
        self.tick_enemies(dt)
        self.remove_enemies()

    def update_score(self, dt: float):
        self.score += dt * 10

    def update_platform(self, dt: float):
        delta = -dt * self.enemy_velocity
        self.platform.move(delta)

    def update(self, dt: float):
        self.update_dino(dt)
        self.update_enemies(dt)
        self.update_score(dt)
        self.update_platform(dt)
        self.sky.tick(dt)

    def tick(self, timedelta: float):
        if self.dino.alive:
            self.update(timedelta)
        self.draw()

    def display_score(self):
        c = self.win.canvas
        c.create_text(c.winfo_width() - 10,
                      20,
                      text=f'Score: {int(self.score)}',
                      anchor=tkinter.E,
                      font=("Purisa", 24))

    def display_game_over(self):
        c = self.win.canvas
        c.create_text(c.winfo_width() // 2,
                      c.winfo_height() // 2,
                      text='Game Over',
                      font=("Purisa", 80))
        c.create_text(c.winfo_width() // 2,
                      c.winfo_height() // 2 + 60,
                      text='Press space to play again',
                      font=("Purisa", 25))

    def draw(self):
        self.win.clear()
        self.win.draw(self.sky)
        self.win.draw(self.platform)
        for enemy in self.enemies:
            self.win.draw(enemy)
        if self.dino:
            self.win.draw(self.dino)
        if not self.dino.alive:
            self.display_game_over()
        self.display_score()
        self.win.update()

    def change_ground(self, path):
        self.platform.load_sprite(path)

    def add_player(self, dino: Dino):
        self.dino = dino

    def add_enemy(self, enemy):
        self.enemies.append(enemy)

    def increase_speed(self):
        self.enemy_velocity += 100
示例#8
0
class Pong(Game):
    """Implements the pong game."""

    def __init__(self, player1, player2):
        """Initialize the game."""
        Game.__init__(self)
        self.__ball = GameBall(400, 300, 10)
        self.__restart_ball()
        self.__paddles = [Paddle((20, 150), (5, 260), (200, 200, 200)),
                          Paddle((20, 150), (775, 260), (200, 200, 200))]
        self.window = Window(800, 600)
        self.window.set_title("Pong")
        self.add_object(self.__ball)
        for p in self.__paddles:
            self.add_object(p)
        self.__scores = [0, 0]
        self.digits = [Text(i, 48) for i in range(10)]

    def __restart_ball(self):
        self.__ball.position = (400, 300)
        self.__ball.movement = (choice([-0.5, 0.5]), choice([-0.5, 0.5]))

    def __ball_collision(self):
        c = collider.wall_circle_collision(self.window.bounds,
                                           self.__ball.bounds)
        dx, dy = self.__ball.movement
        dy *= -1 if {Wall.NORTH, Wall.SOUTH} & c else 1
        # paddles
        sx = -1 if dx < 0 else 1
        for p in self.__paddles:
            if collider.circle_rect_colision(self.__ball.bounds, p.bounds):
                dx = -1 * sx * (abs(dx) + 0.1)
        self.__ball.movement = (dx, dy)
        # walls
        if Wall.WEST in c:
            self.__scores[0] += 1
            self.__restart_ball()
        if Wall.EAST in c:
            self.__scores[1] += 1
            self.__restart_ball()

    def __paddle_collision(self):
        for p in self.__paddles:
            dx, dy = p.movement
            if collider.wall_rect_collision(self.window.bounds, p.bounds):
                dy *= -1
            p.movement = (dx, dy)

    def _update(self):
        """Update objects."""
        self.__ball_collision()
        self.__paddle_collision()
        Game._update(self)

    def _draw(self):
        self.window.clear()
        third = self.window.width // 3
        for i, s in enumerate(self.__scores):
            x = (2 - i)*third
            for c in str(s):
                d = self.digits[int(c)]
                d.position = (x, 5)
                x += d.rect.width + 2
                self.window.draw(d)
        Game._draw(self, False)
示例#9
0
def main():
    random.seed(time.time())

    # Initialise colorama
    init()

    # Clear screen
    print(chr(27) + '[2j')
    print('\033c')
    print('\x1bc')

    # Get terminal size
    (ncols, nlines) = shutil.get_terminal_size()

    # Initialise screen
    screen = Window(0, 1, ncols, nlines - 1, f"{config.bkgd} ")

    # Initialise keyboard
    kb = KBHit()

    # Create and draw the paddle
    paddle = Paddle(((ncols - 1) - config.paddle["dim"][0]) // 2, nlines - 4,
                    screen)

    last_update = 0
    start = time.time()
    score = 0
    lives = 3
    curr_level = 1

    # List to store shooters
    shooters = [None, None]
    while curr_level <= 3:
        # Create and draw bricks
        boss = None
        if curr_level == 1:
            bricks, powerups = levels.level_one(screen)
        elif curr_level == 2:
            bricks, powerups = levels.level_two(screen)
        elif curr_level == 3:
            bricks, powerups = levels.level_three(screen)
            boss = Boss(ncols // 2, 5, screen)
        else:
            sys.exit()

        if lives == 0:
            break

        while lives:
            # Reset paddle location
            paddle.x = ((ncols - 1) - config.paddle["dim"][0]) // 2
            paddle.powerup = None

            # Create and draw the ball
            balls = [
                Ball(random.randrange(paddle.x, paddle.x + paddle.width),
                     nlines - 5, list(config.ball["speed"]), 1, screen)
            ]

            # List to store bullets
            bullets = []
            shoot_paddle = [0]

            # List to store bombs
            bombs = []

            tick = 0
            while len(balls):
                if (time.time() - last_update > config.tick_interval):
                    tick += 1
                    for i in range(ncols):
                        print(f"{Cursor.POS(1+i, 1)}{Back.BLACK} ", end='')

                    statusline = f"{Cursor.POS(1, 1)}Level: {curr_level}   "
                    statusline += f"Score: {score}   "
                    statusline += f"Time: {int(time.time() - start)}   "
                    statusline += f"Lives: {lives}   "
                    statusline += f"Shoot Paddle: {int(shoot_paddle[0] * config.tick_interval)}   "
                    if boss:
                        statusline += "Boss Health: ["
                        for i in range(0, boss.health, 10):
                            statusline += "•"
                        for i in range(0, 100 - boss.health, 10):
                            statusline += " "
                        statusline += "]"
                    print(statusline, end='')

                    last_update = time.time()

                    change_level = False
                    direction = 0
                    if kb.kbhit():
                        c = kb.getch()
                        if ord(c) == 27:
                            sys.exit(0)

                        if c == 'a':
                            direction = -1
                        elif c == 'd':
                            direction = 1
                        elif c == ' ':
                            # Activate balls
                            for ball in balls:
                                ball.paused = False
                        elif c == '1' or c == '2' or c == '3':
                            curr_level = int(c) if curr_level != 3 else 4
                            change_level = True
                            break

                    # Create new bullets if needed
                    shoot_paddle[0] = max(0, shoot_paddle[0] - 1)
                    if shoot_paddle[0] and shoot_paddle[0] % config.bullet[
                            "rate"] == 0:
                        bullets.append(
                            Bullet(max(paddle.x, 0), paddle.y,
                                   config.bullet["speed"], screen))
                        bullets.append(
                            Bullet(
                                min(paddle.x + paddle.width,
                                    screen.get_screen_size()[1] - 1), paddle.y,
                                config.bullet["speed"], screen))

                    # Create bomb if needed
                    if boss and tick % config.bomb["rate"] == 0:
                        bombs.append(
                            Bomb(boss.x + 5, boss.y + 3, config.bomb["speed"],
                                 screen))

                    # Create shooters if needed
                    if shoot_paddle[0] and not shooters[0]:
                        shooters[0] = Object(paddle.x, paddle.y - 1, 1, 1,
                                             config.paddle["color"], screen)
                    if shoot_paddle[0] and not shooters[1]:
                        shooters[1] = Object(paddle.x + paddle.width - 1,
                                             paddle.y - 1, 1, 1,
                                             config.paddle["color"], screen)

                    # Create brick layer on boss level if health is 50
                    if boss and boss.health == 80 and not boss.done[0]:
                        bricks.append([])
                        brick_count = screen.get_screen_size()[1] // \
                            (config.brick["dim"][0] + 5)
                        for i in range(brick_count):
                            bricks[1].append(
                                Brick(i * (config.brick["dim"][0] + 5), 9, 1,
                                      screen))
                        boss.done[0] = True

                    # Create brick layer on boss level if health is 20
                    if boss and boss.health == 20 and not boss.done[1]:
                        brick_count = screen.get_screen_size()[1] // \
                            (config.brick["dim"][0] + 5)
                        bricks.append([])
                        for i in range(brick_count):
                            bricks[2].append(
                                Brick(i * (config.brick["dim"][0] + 5), 13, 1,
                                      screen))
                        boss.done[1] = True

                    # Clear screen
                    screen.clear()

                    # Move the paddle
                    paddle.move(direction, balls)

                    # Move the powerups
                    to_delete = []
                    for powerup in powerups:
                        object = None
                        if powerup.type == "paddle":
                            object = paddle
                        elif powerup.type == "ball":
                            object = balls
                        else:
                            object = shoot_paddle

                        if not powerup.move(paddle, object, tick):
                            to_delete.append(powerup)

                    powerups = [
                        powerup for powerup in powerups
                        if powerup not in to_delete
                    ]

                    # Move the ball
                    to_delete = []
                    for ball in balls:
                        delete, d_score = ball.move(bricks, paddle, boss)
                        if not delete:
                            to_delete.append(ball)

                        score += d_score

                    balls = [ball for ball in balls if ball not in to_delete]

                    # Delete shooters if powerup is over
                    if shoot_paddle[0] == 0:
                        shooters = [None, None]

                    # Move the bullets
                    to_delete = []
                    for bullet in bullets:
                        delete, d_score = bullet.move(bricks)
                        if not delete:
                            to_delete.append(bullet)

                        score += d_score

                    bullets = [
                        bullet for bullet in bullets if bullet not in to_delete
                    ]

                    # Move the bombs
                    to_delete = []
                    lose_life = False
                    for bomb in bombs:
                        delete, lose_life = bomb.move(paddle)
                        if not delete:
                            to_delete.append(bomb)
                        if lose_life:
                            break

                    if lose_life:
                        break

                    bombs = [bomb for bomb in bombs if bomb not in to_delete]

                    # Move the boss
                    if boss:
                        boss.move(paddle.x + paddle.width // 2)

                    # Move the shooter
                    if shooters[0]:
                        shooters[0].x = paddle.x
                    if shooters[1]:
                        shooters[1].x = paddle.x + paddle.width - 1

                    # Update bricks
                    for layer in bricks:
                        for brick in layer:
                            brick.rainbow(tick)
                            # Don't move bricks on boss level
                            if curr_level < 3:
                                brick.move(tick)
                            if brick.y + brick.height > paddle.y:
                                sys.exit()
                            brick.update()

                    # Update paddle
                    paddle.update()

                    # Update shooters
                    for shooter in shooters:
                        if shooter:
                            shooter.update()

                    # Update powerups
                    for powerup in powerups:
                        powerup.update()

                    # Update ball
                    for ball in balls:
                        ball.update()

                    # Update bullets
                    for bullet in bullets:
                        bullet.update()

                    # Update bombs
                    for bomb in bombs:
                        bomb.update()

                    # Boss update
                    if boss:
                        boss.update()

                    screen.draw()

                    # Check if all breackable bricks are broken on non boss levels
                    if curr_level < 3:
                        change_level = True
                        for layer in bricks:
                            for brick in layer:
                                if brick._strength != 4:
                                    change_level = False
                                    break
                            if not change_level:
                                break
                    else:
                        if boss.health <= 0:
                            change_level = True

                    if change_level:
                        curr_level += 1
                        break

            if change_level:
                break

            lives -= 1
示例#10
0
#         return self.x + 0.5 * self.width


n, a, b = map(int, input().split())
a1 = a2 = a

rect = Rectangle(randint(15, 95), randint(15, 800), a, b)
square = Square(randint(15, 95), randint(15, 800), a1)
circle = Circle(randint(15, 95), randint(15, 800), a2)
shapes = [rect, square, circle]
velocity = randint(4, 10)

while not window.closed:
    # frame start
    start = time()
    window.clear()  # clear window before redraw

    # redraw frame
    for num in range(n):
        alt = randint(0, 2)
        shapes[alt].x += velocity
        if shapes[alt].right() > window.width:
            velocity = -4
        elif shapes[alt].left() < 0:
            velocity = 4
        elif shapes[alt].top() > 0:
            velocity = 4
        elif shapes[alt].bottom() < window.width:
            velocity = -4
        rect.draw()