def main(): pygame.init() screen = display.set_mode(DISPLAY, FLAGS, DEPTH) display.set_caption("Use arrows to move!") timer = time.Clock() up = down = left = right = space = False bg = Surface((BLOCK_SIZE, BLOCK_SIZE)) bg.convert() bg.fill(Color("#000000")) current_level = Level(LEVEL_W, LEVEL_H) player = Player(100, 100) entities = pygame.sprite.Group() entities.add(player) while True: timer.tick(FPS) for e in pygame.event.get(): if e.type == QUIT: raise SystemExit, "QUIT" if e.type == KEYDOWN and e.key == K_ESCAPE: raise SystemExit, "ESCAPE" if e.type == KEYDOWN and e.key == K_UP: up = True if e.type == KEYDOWN and e.key == K_DOWN: down = True if e.type == KEYDOWN and e.key == K_LEFT: left = True if e.type == KEYDOWN and e.key == K_RIGHT: right = True if e.type == KEYDOWN and e.key == K_SPACE: space = True if e.type == KEYUP and e.key == K_UP: up = False if e.type == KEYUP and e.key == K_DOWN: down = False if e.type == KEYUP and e.key == K_LEFT: left = False if e.type == KEYUP and e.key == K_RIGHT: right = False if e.type == KEYUP and e.key == K_SPACE: space = False if e.type == MOUSEBUTTONUP: pos = pygame.mouse.get_pos() print current_level._identify_img(pos[0]/BLOCK_SIZE, pos[1]/BLOCK_SIZE) # draw background for y in range(LEVEL_H): for x in range(LEVEL_W): screen.blit(bg, (x * BLOCK_SIZE, y * BLOCK_SIZE)) # update player, draw everything else player.update(up, down, left, right, space, current_level) player.draw(screen) #entities.draw(screen) current_level.draw(screen) pygame.display.flip()
screen.blit(label, label_rect) screen.blit(text, text_rect) # cheeky way to update the integer position at a slower rate speed = 0 # game loop running = True while running: # update game entities speed += 1 if speed >= 5: speed = 0 if player.is_moving: player.update() for bullet in bullets: bullet.update() for enemies in squadron: for enemy in enemies: enemy.update() # react to events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
class OrcInvader(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) self.set_mouse_visible(False) arcade.set_background_color(arcade.color.ASH_GREY) self.frame_count = 0 self.player_list = None self.player_bullet_list = None self.enemy_list = None self.enemy_bullet_list = None self.player = None self.score = 0 self.current_state = GameState.RUNNING def setup(self): self.player_list = arcade.SpriteList() self.player_bullet_list = arcade.SpriteList() self.enemy_list = Enemies.setup(ENEMY_COUNT) self.enemy_bullet_list = arcade.SpriteList() self.player = Player() self.player_list.append(self.player) def draw_message(self, text, color): arcade.draw_text(text, SCREEN_WIDTH / 2., SCREEN_HEIGHT / 2., color, 54, align="center", anchor_x="center", anchor_y="center") def draw_game(self): self.enemy_list.draw() self.enemy_bullet_list.draw() self.player_list.draw() self.player_bullet_list.draw() output = f"Score: {self.score}" arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) def on_draw(self): arcade.start_render() self.draw_game() if self.current_state is GameState.PAUSED: self.draw_message("Game Paused", arcade.color.WHITE) elif self.current_state is GameState.GAME_OVER: self.draw_message("Game Over", arcade.color.RED) elif self.current_state is GameState.FINISHED: self.draw_message("WON", arcade.color.GREEN) def update(self, delta_time): if self.current_state is GameState.RUNNING: self.player.update() self.enemy_list.update() hit_list = arcade.check_for_collision_with_list( self.player, self.enemy_list) if hit_list: self.current_state = GameState.GAME_OVER self.enemy_bullet_list.update() self.player_bullet_list.update() if not self.enemy_list: self.current_state = GameState.FINISHED for enemy in self.enemy_list: # use assignment expression once 3.8 is released bullet = enemy.shoot() if bullet: self.enemy_bullet_list.append(bullet) if enemy.top < 0: self.current_state = GameState.GAME_OVER for bullet in self.player_bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.enemy_list) if len(hit_list) > 0: bullet.kill() for enemy in hit_list: enemy.kill() self.score += 1 if bullet.bottom > SCREEN_HEIGHT: bullet.kill() for bullet in self.enemy_bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.player_list) if hit_list: self.current_state = GameState.GAME_OVER if bullet.top < 0: bullet.kill() def on_key_press(self, key, modifiers): if key == arcade.key.LEFT: self.player.change_x = -MOVEMENT_SPEED elif key == arcade.key.RIGHT: self.player.change_x = MOVEMENT_SPEED elif key == arcade.key.SPACE: self.player_bullet_list.append(self.player.shoot()) elif key == arcade.key.P: self.toggle_pause() elif key == arcade.key.Q: sys.exit() def on_key_release(self, key, modifiers): if key == arcade.key.LEFT or key == arcade.key.RIGHT: self.player.change_x = 0 def toggle_pause(self): if self.current_state is GameState.PAUSED: arcade.start_render() self.current_state = GameState.RUNNING else: arcade.finish_render() self.current_state = GameState.PAUSED
def main(): """ Main Program """ pygame.init() # # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] # # Set display screen screen = pygame.display.set_mode(size) pygame.display.set_caption("Game") # # Create world world = World() sprite_group = pygame.sprite.Group() sprite_group_2 = pygame.sprite.Group() # # Create the player player = Player() enemy = Enemy() # # Create Walls wall = Wall(500, 400, 100, 100) wall2 = Wall(100, 100, 50, 50) # # Group sprite_group.add(wall) sprite_group.add(wall2) sprite_group_2.add(enemy) player.walls = sprite_group player.enemies = sprite_group_2 # Loop until the user clicks the close button. done = False # # Get keys pressed_right = None pressed_left = None pressed_up = None pressed_down = None # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: done = True elif event.key == pygame.K_RIGHT: pressed_right = True elif event.key == pygame.K_LEFT: pressed_left = True elif event.key == pygame.K_UP: pressed_up = True elif event.key == pygame.K_DOWN: pressed_down = True elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: pressed_right = False elif event.key == pygame.K_LEFT: pressed_left = False elif event.key == pygame.K_UP: pressed_up = False elif event.key == pygame.K_DOWN: pressed_down = False player.update(pressed_right, pressed_left, pressed_up, pressed_down) # # Go ahead and update the screen with what we've drawn. world.world_shift(player.rect.x, player.rect.y) screen.fill(constants.WHITE) screen.blit(world.image, world.rect) sprite_group.draw(screen) screen.blit(player.image, player.rect) pygame.draw.rect(screen, constants.GREEN, (10, 10, 60, 10)) enemy.move_enemy(player.rect.x, player.rect.y) # screen.blit(enemy.image, enemy.rect) sprite_group_2.draw(screen) pygame.display.flip() # Limit to 60 frames per second clock.tick(60) # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
class Level1(Level): """ first level become the biggest """ def __init__(self, game: Properties): super().__init__(game) def level_init(self): self.player = Player(20, random.randint(20, game_width - 20), random.randint(20, game_height - 20)) self.player.game = self.game self.enemies = [ Sphere(random.randint(2, 40), random.randint(40, game_width - 40), random.randint(40, game_height - 40)) for x in range(200) ] # spawn random enemies for enemy in self.enemies: enemy.speed(random.randint(-1, 1), random.randint( -1, 1)) # set random speed to reduce impasse def run_level(self): while self.running: self.game.screen.fill( (0, 0, 255)) # background outside level space self.game.screen.blit( pygame.transform.scale(background, (round(game_width * self.scale), round(game_height * self.scale))), (round(-(self.player.x * self.scale - self.player.pos()[0])), round(-(self.player.y * self.scale - self.player.pos()[1])) )) # level space backgorund sync with player position if not self.user_interaction_handler(): return if self.clicks > 0: # very rudimentary way of knowing number of rapid clicks self.clicks -= 1 if not self.paused: if self.player.size < 1: return game_over(self.game) pygame.draw.circle(self.game.screen, (0, 30, 255), self.player.pos(), self.player.scaled_size()) self.player.update() for enemy in self.enemies.copy(): pygame.draw.circle(self.game.screen, enemy.color, enemy.pos(), enemy.scaled_size()) if not enemy.update(): self.enemies.remove(enemy) for enemy in self.enemies + [self.player]: for enemy2 in self.enemies + [self.player]: if enemy2 != enemy: if collision(enemy, enemy2): attack(enemy, enemy2) pygame.draw.circle(self.game.screen, (150, 150, 150), [ pos + (self.player.scaled_size() * 1.5) * dir for pos, dir in zip(self.player.pos(), get_trig(self.player)) ], 5) if all([ self.player.size > enemy.size for enemy in self.enemies ]) and not self.won: # check if user is the biggest self.won = true self.paused = true else: if self.won: if not pause_menu(self.game, won=true): return false else: self.paused = false else: if not pause_menu(self.game): return false else: self.paused = false pygame.display.update() self.game.clock.tick(self.game.fps)
class LlnRpg: """ A class gathering all the information needed by the game to run. This class act as a place to store everything we need for our asynchronous functions without need for a large amount of argument or global variables. Some of the functions from this class are asynchronous. If you want to dig into the code and the way it works, you will first need to see the python doc's section about asynchronous programming in python. :[class] monitoring_data: A dictionary storing monitored data about the game execution. :grid_width: The width (in tiles) of the grid. :grid_height: The height (in tiles) of the grid. :screen: The pygame.Surface object representing the screen. :grid: The Grid object representing the map. :player: the Player object representing the player. :sound_button: The pygame.Surface object representing the sound button. :sound_button_box: The pygame.Rect object representing the sound button's hitbox. :sound_played: True if sound is played, False if muted. :running: True if game is running, False otherwise. """ key_direction_mapping = { pygame.locals.K_UP: 0, pygame.locals.K_DOWN: 1, pygame.locals.K_LEFT: 2, pygame.locals.K_RIGHT: 3, pygame.locals.K_s: 1, pygame.locals.K_d: 3, } monitoring_data = { 'events': 0.0, 'handled-events': 0.0, 'clicks': 0.0, 'handled-clicks': 0.0, 'frames': 0.0, 'handle_events-loops': 0.0, 'monitoring-interval': 0.0, 'player-balance': 0.0, 'entity-number': 0.0, } def __init__(self, **kwargs): """ All arguments are keyword-arguments. All have default values (in parenthesis), even if not specified. :param azerty: True if keyboard entry is azerty, False for qwerty (True). :param grid_width: Grid width in tiles (30). :param grid_height: Grid height in tiles (20). :param screen_mode: Screen size (960, 640). :param map_file: .map file describing the map ('level.map'). :param map_pos: coordinates of the top left corner of the map, relative to the top left corner of the screen (128, 64). :param play_sound: True to start playing sound, False to start with sound muted (False). :param base_delay: Minimal delay to wait between each asynchronous call of the same function. Useless to give < 1e-4. This should not be changed since it affects a lot the way the game behave and its performances (1e-3). """ self.azerty = kwargs.get('azerty', True) if self.azerty: self.key_direction_mapping[pygame.locals.K_z] = 0 self.key_direction_mapping[pygame.locals.K_q] = 2 else: self.key_direction_mapping[pygame.locals.K_w] = 0 self.key_direction_mapping[pygame.locals.K_a] = 2 self.grid_width = kwargs.get('grid_width', 30) self.grid_height = kwargs.get('grid_height', 20) self.screen = pygame.display.set_mode(kwargs.get('screen_mode', (960, 640))) self.grid = Grid(kwargs.get('map_file', "level.map"), self.screen, (self.grid_width, self.grid_height), kwargs.get('map_pos', (32*4, 32*2))) self.player = Player(self.screen, self.grid, 'male') # Create coins for p in [(8, 10), (9, 11), (10, 10), (8, 12), (10, 12)]: coin = Coin(tuple(numpy.multiply(self.grid.tilesize, 0.75)), 10) coin.load_sprites('res/coin.png', 1, 1) coin.set_pos(self.grid, p) self.grid.add_entity(coin) # Array storing arrow key inputs self.raw_direction = [0, 0, 0, 0] # init button and its hitbox variable, assigned in toggle_sound self.sound_button = self.sound_button_box = None self.running = False self.sound_played = not kwargs.get('play_sound', False) # Useless to go < 1e-4, this controls game tick speed # (roughly, not the same as fps) # Think of it as "how fast will the game compute things" self.base_delay = kwargs.get('base_delay', 1e-3) async def monitoring(self): """ An asynchronous loop function used for monitoring and debug. Data entries can be added to the class-attribute monitoring_data and processed and/or printed out in this function. This function may also be used to check program's status and sanity. """ while self.running: elapsed = time.time() await asyncio.sleep(1) # Gather some data self.monitoring_data['player-balance'] = self.player.balance # all entities + player self.monitoring_data['entity-number'] = len(self.grid.entities) + 1 # Computing elapsed time during the asynchronous waiting time elapsed = time.time() - elapsed # Printing the whole data dictionary self.monitoring_data['monitoring-interval'] = elapsed print('MONITORING:') for k, v in self.monitoring_data.items(): print('[] ' + k + ': ' + str(v)) print('') # Resetting for k, v in self.monitoring_data.items(): self.monitoring_data[k] = 0.0 print('Closed monitoring') async def handle_mouse(self): """ An asynchronous loop function to handle mouse interactions. This functions check when the user clicks and tell the game what to do then. """ while self.running: # Wait until mouse left clicks # get_pressed returns a 3-tuple for left, middle and right click. while self.running and not (pygame.mouse.get_focused() and pygame.mouse.get_pressed()[0]): await asyncio.sleep(self.base_delay) # Get mouse position relative to top left corner of the screen x, y = pygame.mouse.get_pos() # If click was on the sound button if self.sound_button_box.collidepoint(x, y): self.toggle_sound() self.monitoring_data['handled-clicks'] += 1 # wait until mouse unpressed while self.running and pygame.mouse.get_pressed()[0]: await asyncio.sleep(self.base_delay) self.monitoring_data['clicks'] += 1 await asyncio.sleep(self.base_delay) # avoiding too fast spam click print('Closed mouse handler') async def handle_graphics(self): """ An asynchronous loop function that draws map and sprites onto the screen. This function calls all the update functions of the entities in the map, including the player, first, then draw. """ while self.running: # Update player self.player.update(get_direction(self.raw_direction), self.grid) # Update coordinates of the view self.grid.view_coord = ( self.player.screen_pos[0] - self.player.map_pos[0], self.player.screen_pos[1] - self.player.map_pos[1] ) # Draw map in the background self.screen.blit(self.grid.background, self.grid.view_coord) # Draw player self.player.blit(self.screen, self.grid.view_coord) # Update and draw entities # creating list avoids error if dict size changes, which happen # when entities delete themselves grid_entities = [entity for _, entity in self.grid.entities.items()] for entity in grid_entities: # print(entity) entity.update(self.grid) entity.blit(self.screen, self.grid.view_coord) # Draw sound button self.screen.blit(self.sound_button, (0, 0)) # Actually display what was drawn pygame.display.flip() self.monitoring_data['frames'] += 1 # Wait until next frame await asyncio.sleep(0.015) # This controls fps (roughly) print('Closed graphics handler') async def handle_events(self): """ An asynchronous loop function that process events. """ while self.running: # Poll each event pushed to the event queue for event in pygame.event.get(): # Quit event if event.type == pygame.QUIT: self.running = False self.monitoring_data['handled-events'] += 1 # Key pressed event, arrow key pressed if event.type == pygame.locals.KEYDOWN \ and event.key in self.key_direction_mapping: # Update pressed key as being the last pressed key # (in case several are pressed simultaneously) self.raw_direction[self.key_direction_mapping[ event.key]] = max(self.raw_direction) + 1 self.monitoring_data['handled-events'] += 1 # Key unpressed event, arrow key unpressed elif event.type == pygame.locals.KEYUP \ and event.key in self.key_direction_mapping: # Key is unpressed, so it should be taken into account # anymore in player direction computation self.raw_direction[self.key_direction_mapping[ event.key]] = 0 self.monitoring_data['handled-events'] += 1 # Key pressed event, space bar pressed elif event.type == pygame.locals.KEYDOWN \ and event.key == pygame.locals.K_SPACE: self.player.running = not self.player.running self.monitoring_data['handled-events'] += 1 self.monitoring_data['events'] += 1 self.monitoring_data['handle_events-loops'] += 1 await asyncio.sleep(self.base_delay) print('Closed events handler') def main(self): """ Main function that initiates and runs the game. Launch asynchronous tasks and wait them to finish. """ pygame.init() pygame.display.set_caption("RPG - Louvain-la-Neuve") # Draw the map on the screen, as a background self.screen.blit(self.grid.background, self.grid.view_coord) pygame.display.flip() # load music pygame.mixer.init() pygame.mixer.music.load("sound/lln_sound.wav") self.toggle_sound() async def gather_tasks(): # Inner function to gather all coroutines in a single awaitable. await asyncio.gather( self.handle_events(), self.handle_mouse(), self.handle_graphics(), self.monitoring() ) # Start running the game self.running = True asyncio.run(gather_tasks()) print('Exit main') def toggle_sound(self): """ Toggles the sound playing and the appearance of the corresponding button at each call. """ if self.sound_played: self.sound_button = pygame.image.load("images/no_sound_icon.png") self.sound_button = pygame.transform.scale(self.sound_button, (32, 32)) pygame.mixer.music.stop() self.sound_played = False else: self.sound_button = pygame.image.load("images/sound_icon.png") self.sound_button = pygame.transform.scale(self.sound_button, (32, 32)) pygame.mixer.music.play(-1, 0.0) self.sound_played = True if self.sound_button_box is None: self.sound_button_box = self.sound_button.get_rect()
class Game(States): def __init__(self): States.__init__(self) self.next = 'gameover' self.player = Player(self) self.platforms = pg.sprite.Group() self.all_sprites = pg.sprite.Group() self.all_sprites.add(self.player) self.PLATFORM_LIST = [Platform(0, HEIGHT - 40, 150, 10), Platform(950, 850, 150, 10), Platform(950, 650, 150, 10), Platform(950, 450, 150, 10), Platform(950, 250, 150, 10), Platform(950, 50, 150, 10)] self.create_plat() self.score = 0 self.load_data() def cleanup(self): print('cleaning up Game Level One state stuff') States.__init__(self) self.next = 'gameover' self.player = Player(self) self.platforms = pg.sprite.Group() self.all_sprites = pg.sprite.Group() self.all_sprites.add(self.player) self.PLATFORM_LIST = [Platform(0, HEIGHT - 40, 150, 10), Platform(950, 850, 150, 10), Platform(950, 650, 150, 10), Platform(950, 450, 150, 10), Platform(950, 250, 150, 10), Platform(950, 50, 150, 10)] self.create_plat() self.score = 0 self.load_data() def startup(self): print('starting Game Level One state stuff') def get_event(self, event): if event.type == pg.KEYDOWN: print('Game Level One State keydown') if event.type == pg.MOUSEBUTTONDOWN: pg.mixer.music.play() self.done = True if event.type == pg.KEYDOWN: if event.key == pg.K_w: self.player.jump() def load_data(self): #Load the high score. with open((HS_FILE), 'r') as f: try: self.highscore = int(f.read()) except: self.highscore = 0 def update(self, screen, dt): self.draw(screen) self.player.update() self.player.runAnim(dt) if self.player.vel.y > 0: hits = pg.sprite.spritecollide(self.player, self.platforms, False) if hits: self.player.pos.y = hits[0].rect.top + 1 self.player.vel.y = 0 #Scrolling functionality. if self.player.rect.top <= HEIGHT / 4: self.player.pos.y += max(abs(self.player.vel.y), 2) for plat in self.platforms: plat.rect.y += max(abs(self.player.vel.y), 2) if plat.rect.top >= HEIGHT: plat.kill() self.score += 10 if self.score > self.highscore: self.highscore = self.score with open((HS_FILE), 'w') as f: f.write(str(self.score)) if self.player.rect.bottom > HEIGHT: for sprite in self.all_sprites: sprite.rect.y -= max(self.player.vel.y, 10) if sprite.rect.bottom < 0: sprite.kill() if len(self.platforms) == 0: pg.mixer.music.play() self.done = True #Spawn new platforms. while len(self.platforms) < 10: width = random.randrange(50, 150) p = Platform(random.randrange(0, WIDTH-width), random.randrange(-75, -30), 150, 10) self.platforms.add(p) self.all_sprites.add(p) def create_plat(self): for platform in self.PLATFORM_LIST: self.platforms.add(platform) self.all_sprites.add(platform) def draw_text(self, text, size, color, x, y): self.font = loadCustomFont('Fonts/Amatic_SC/amatic_sc.ttf', 72) text_surface = self.font.render(text, True, color) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) screen.blit(text_surface, text_rect) def draw(self, screen): screen.fill((255, 255, 0)) #Draw the test platform. for plat in self.platforms: plat.draw() #Draw the player. self.player.draw() self.draw_text('Score: ' + str(self.score), 12, (0,0,0), 125, 10) self.draw_text('Highscore: ' + str(self.highscore), 22, (0,0,0), 1750, 10)
class Game(Widget): temp_text = StringProperty("") temp_textlist = ListProperty(["", "", "", ""]) def gamesetup(self): # Setting up the Event Handler. self.events = EventHandler() self.events.calls["keydown"] = self.key_down self.events.calls["keyup"] = self.key_up self.events.calls["mouseover"] = self.mouse_over self.events.eventsetup() # Setting up the Menu controller. self.menus = Menus(size=self.size) self.menus.menusetup() # Setting up the NPCs. self.npcs = NPCController() self.npcs.controllersetup() # Setting up the Player. self.player = Player() self.player.playersetup(Window.size) self.player.place(Window.center[0], Window.center[1]) # Setting up the Dialogue controller. self.dialogue = Dialogue() self.dialogue.dialoguesetup() # Setting up the world. self.world = World() self.world.worldcenter = self.center self.world.setupworld((768 * 3, 608 * 3)) # Adding everything to the Widget stack self.add_widget(self.events) self.world.add_npcs(self.npcs.npcgroup) self.world.add_widget(self.player) self.add_widget(self.world) self.add_widget(self.menus) self.add_widget(self.dialogue) # Centering Screen on the player self.center_screen(0.2) def center_screen(self, delay=0.1): Clock.schedule_once(self.world.center_screen, delay) def update(self, dt): self.menus.update(dt) self.npcs.update(dt) self.player.update(dt) def mouse_over(self, pos): pass def key_down(self, key, mod): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keydown(key[1]) elif key[1] == "spacebar": print(self.player.pos, self.player.center) def key_up(self, key): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keyup(key[1]) def begin_conv(self, npc): self.dialogue.npc = npc self.dialogue.start_conv() self.menus.menu_on = not self.menus.menu_on def change_top_text(self, txt): """ Top text area contains only one piece of text at a time. """ self.temp_text = txt self.menus.fade_out_top = True def change_bottom_text(self, txtlist): """ Bottom Text contains 4 question areas. """ for num, _ in enumerate(self.menus.bottomtext): try: self.menus.bottomtext[num] = txtlist[num] except IndexError: self.menus.bottomtext[num] = "" self.menus.fade_out_bottom = True
if bullet.moving: bullet.update(delta_time_scalar) pygame.draw.rect(board, bullet.colour, bullet) else: bullets.remove(bullet) # Draw board to screen display.blit(board, (board.x, board.y)) # Draw enemies to screen for enemy in enemies: display.blit(enemy, (enemy.x, enemy.y)) # Draw player to screen mx, my = pygame.mouse.get_pos() player.update(mx, my) display.blit(player, (player.x, player.y)) # Draw melee swing to screen if hotbar[hotbar.selected_pos][1] != melee_swing.item: melee_swing = MeleeSwing(player, hotbar[hotbar.selected_pos][1]) melee_swing.update() p_rect = pygame.Rect(player.x + (player.width // 2), player.y + (player.height // 2), player.width, player.height) melee_swing.x = p_rect.centerx - (melee_swing.width // 2) melee_swing.y = p_rect.centery - (melee_swing.height // 2) display.blit(melee_swing, (melee_swing.x, melee_swing.y)) # Update hotbar surface and draw to screen hotbar.update()
class Level2(Level): """ eat the Repulsor """ def __init__(self, game: Properties): super().__init__(game) def level_init(self): self.player = Player(30, random.randint(30, game_width - 30), random.randint(30, game_height - 30)) self.player.game = self.game self.enemies = [ Sphere(random.randint(2, 20), random.randint(20, game_width - 20), random.randint(20, game_height - 20)) for x in range(100) ] self.repulsor = Repulsor(30, random.randint(30, game_width - 30), random.randint(30, game_height - 30)) for enemy in self.enemies + [self.repulsor]: enemy.speed(random.randint(-1, 1) / 1, random.randint(-1, 1) / 1) def run_level(self): while self.running: self.game.screen.fill((0, 0, 255)) self.game.screen.blit( pygame.transform.scale(background, (round(game_width * self.scale), round(game_height * self.scale))), (round(-(self.player.x * self.scale - self.player.pos()[0])), round(-(self.player.y * self.scale - self.player.pos()[1])))) if not self.user_interaction_handler(): return if self.clicks > 0: self.clicks -= 1 if not self.paused: if self.player.size < 1: return game_over(self.game) pygame.draw.circle(self.game.screen, (0, 255, 255), self.player.pos(), self.player.scaled_size()) self.player.update() for enemy in self.enemies.copy() + [self.repulsor]: if enemy == self.repulsor and self.repulsor.size > 1: pygame.draw.circle(self.game.screen, (255, 255, 255), enemy.pos(), enemy.scaled_size()) enemy.update() elif enemy != self.repulsor: pygame.draw.circle(self.game.screen, enemy.color, enemy.pos(), enemy.scaled_size()) if not enemy.update(): self.enemies.remove(enemy) for enemy in self.enemies + [self.player, self.repulsor]: for enemy2 in self.enemies + [self.player, self.repulsor]: if enemy2 != enemy: if enemy == self.repulsor and enemy.size < enemy2.size: enemy.evade( get_trig_general(enemy, enemy2), distance(enemy, enemy2) ) # Repulsor evades from bigger spheres if collision(enemy, enemy2): attack(enemy, enemy2) pygame.draw.circle(self.game.screen, (150, 150, 150), [ pos + (self.player.scaled_size() * 1.5) * dir for pos, dir in zip(self.player.pos(), get_trig(self.player)) ], 5) if self.player.size > self.repulsor.size and self.repulsor.size < 1 and not self.won: self.won = true self.paused = true else: if self.won: if not pause_menu(self.game, won=true): return false else: self.paused = false else: if not pause_menu(self.game): return false else: self.paused = false pygame.display.update() self.game.clock.tick(self.game.fps)
class PingPong: def __init__(self): self.middle_rects = self.create_middle_rects(5, 15) # Initialize entities self.player = Player(20, 20, 100, PLAYER_COLOR) self.enemy = Enemy(SCREEN_WIDTH - 20 - 20, 20, 100, ENEMY_COLOR) self.ball = Ball(12, 600) # Initialize fonts self.score_font = pygame.font.Font("8bit.ttf", SCORE_SIZE) self.player_score_label = self.score_font.render( str(self.player.score), True, SCORE_COLOR) self.enemy_score_label = self.score_font.render( str(self.enemy.score), True, SCORE_COLOR) def update(self, delta): # Update entities self.player.update(delta) self.enemy.update(delta) self.ball.update(delta) # Check if the ball collides with one of both paddles ball_collides_player = (self.ball.rect.colliderect(self.player.rect) and self.ball.velocity.x < 0) ball_collides_enemy = (self.ball.rect.colliderect(self.enemy.rect) and self.ball.velocity.x > 0) if ball_collides_player: self.ball.rect.x = self.player.rect.topright[0] # Clamp the value between 0 and player's height hit_relative_y = max( 0, min(self.ball.rect.topleft[1] - self.player.rect.topright[1], self.player.rect.height)) self.ball.change_angle(hit_relative_y, self.player.rect.height) self.enemy.calculate_next_position(self.ball) elif ball_collides_enemy: self.ball.rect.x = self.enemy.rect.x - self.ball.radius * 2 self.ball.velocity.x *= -1 self.ball.predicted_y = -1 # Increase score and update the label if self.ball.rect.topleft[0] <= 0: self.player.score += 1 self.player_score_label = self.score_font.render( str(self.player.score), True, SCORE_COLOR) self.ball.reset() elif self.ball.rect.topright[0] >= SCREEN_WIDTH: self.enemy.score += 1 self.enemy_score_label = self.score_font.render( str(self.enemy.score), True, SCORE_COLOR) def render(self, screen): # Render scores self.render_scores(screen) self.render_middle_rects(screen) # Render entities self.player.render(screen) self.enemy.render(screen) self.ball.render(screen) """ Returns an array of the rects that appear in the middle of the screen """ def create_middle_rects(self, width, number): rects = [] height = SCREEN_HEIGHT / number / 2 for i in range(number): y = i * height * 2 + height / 2 rect = pygame.Rect((SCREEN_WIDTH - width) / 2, y, width, height) rects.append(rect) return rects def render_middle_rects(self, screen): for rect in self.middle_rects: pygame.draw.rect(screen, MIDDLE_RECTS_COLOR, rect) def render_scores(self, screen): screen.blit(self.player_score_label, PLAYER_SCORE_POSITION) screen.blit(self.enemy_score_label, ENEMY_SCORE_POSITION)
class Game(Widget): temp_text = StringProperty("") temp_textlist = ListProperty(["", "", "", ""]) def gamesetup(self): # Setting up the Event Handler. self.events = EventHandler() self.events.calls["keydown"] = self.key_down self.events.calls["keyup"] = self.key_up self.events.calls["mouseover"] = self.mouse_over self.events.eventsetup() # Setting up the Menu controller. self.menus = Menus(size=self.size) self.menus.menusetup() # Setting up the NPCs. self.npcs = NPCController() self.npcs.controllersetup() # Setting up the Player. self.player = Player() self.player.playersetup(Window.size) self.player.place(Window.center[0], Window.center[1]) # Setting up the Dialogue controller. self.dialogue = Dialogue() self.dialogue.dialoguesetup() # Setting up the world. self.world = World() self.world.worldcenter = self.center self.world.setupworld((768*3, 608*3)) # Adding everything to the Widget stack self.add_widget(self.events) self.world.add_npcs(self.npcs.npcgroup) self.world.add_widget(self.player) self.add_widget(self.world) self.add_widget(self.menus) self.add_widget(self.dialogue) # Centering Screen on the player self.center_screen(0.2) def center_screen(self, delay=0.1): Clock.schedule_once(self.world.center_screen, delay) def update(self, dt): self.menus.update(dt) self.npcs.update(dt) self.player.update(dt) def mouse_over(self, pos): pass def key_down(self, key, mod): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keydown(key[1]) elif key[1] == "spacebar": print(self.player.pos, self.player.center) def key_up(self, key): if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"): self.player.keyup(key[1]) def begin_conv(self, npc): self.dialogue.npc = npc self.dialogue.start_conv() self.menus.menu_on = not self.menus.menu_on def change_top_text(self, txt): """ Top text area contains only one piece of text at a time. """ self.temp_text = txt self.menus.fade_out_top = True def change_bottom_text(self, txtlist): """ Bottom Text contains 4 question areas. """ for num, _ in enumerate(self.menus.bottomtext): try: self.menus.bottomtext[num] = txtlist[num] except IndexError: self.menus.bottomtext[num] = "" self.menus.fade_out_bottom = True
player1.yc = 0 player1.y += player1.yc # Enemy spawn logic for r in rects: size = (randint(25, 200), 25) enemy.x -= enemy.speed if enemy.x < 0: enemy.generate_new(window, size) score += 1 elif enemy.x == player1.x + 25 and enemy.y == player1.y: enemy.speed = 0 window.game_over() print('game') print('Enemy X ' + str(enemy.x) + ', Player X ' + str(player1.x)) score_txt = font.render('Score: ' + str(score), False, (0, 0, 0)) window.display.blit(score_txt, [10, 10]) pygame.display.update() window.display.fill(WHITE) player1.update(window) base.update(window) enemy.update(window) clock.tick(fps)