def __init__(self): self._running = True self._fps = 30 self.window_size = (1000, 600) pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() self.screen = pygame.display.set_mode(self.window_size) self.map_surface = pygame.Surface((800, 600)) self.inventory_surface = pygame.Surface((200, 600)) pygame.display.set_caption("Dungeon-RPG") self.clock = pygame.time.Clock() self.map = Map("map.tmx") # Init camera Cam.x = 800/2-self.map.player.x Cam.y = 600/2-self.map.player.y self.font = pygame.font.Font("media/fonts/munro_small.ttf", 22) self.tooltip = None
def setupCameraMap(self): ''' Sets up camera and map for a given level ''' self.camera = Camera(self.game_screen) self.background = Background(self.game_display) self.game_map = Map(self.game_display, self.screen_dims, 32)
def __init__(self): #setting the pygame window title = "MacGyver's Maze" display = Display(600, 650, title) #Setting the map mapping = Map("mapping.txt") display.set_map(mapping) #Setting the characters bad_guy = Character(1, 14, "guardian.png", mapping) gyver = MacGyver(14, 0, "macgyver.png", mapping) display.set_characters(gyver, bad_guy) pygame.display.flip() self._start_game(mapping, gyver, bad_guy, display)
def __init__(self): """function to set the game : creating the map, placing the items randomly, MacGyver and the Guardian's location must be specified (y, x). Once it's done, starting the game. """ #setting the pygame window title = "MacGyver's Labyrinth" display = Display(600, 650, title) #Setting the map mapping = Map("mapping.txt") display.set_map(mapping) #Setting the characters bad_guy = Character(1, 14, "guardian.png", mapping) gyver = MacGyver(14, 0, "macgyver.png", mapping) display.set_characters(gyver, bad_guy) pygame.display.flip() self._start_game(mapping, gyver, bad_guy, display)
def merge_fields_into_match(fields, match): if match.home.name != fields['home']: log.warning( f"Home team doesn't match: {match.home.name} to {fields['home']}") if match.away.name != fields['away']: log.warning( f"Away team doesn't match: {match.away.name} to {fields['away']}") merge_field(match, "stage", fields['match_name']) merge_field(match, "competition", fields['tournament']) merge_field(match, "competition_url", f"https://www.over.gg{fields['tournament_url']}") if 'vod' in fields: merge_field(match, "vod", fields['vod']) for stream_num in ["stream1", "stream2", "stream3"]: url_name = stream_num + "url" language_name = stream_num + "language" if url_name in fields: matched = False for match_stream in match.streams: if fields[url_name] == match_stream.url: matched = True if not matched: if language_name in fields: language = fields[language_name].strip("()") else: language = None bisect.insort(match.streams, Stream(fields[url_name], language)) log.debug(f"Streams dirty: {fields[url_name]}") match.dirty = True if 'state2' in fields and fields['state2'] == "final": merge_field(match, "state", GameState.COMPLETE) elif 'state' in fields and fields['state'] == "live": merge_field(match, "state", GameState.IN_PROGRESS) else: merge_field(match, "state", GameState.PENDING) if match.state in [GameState.IN_PROGRESS, GameState.COMPLETE]: if 'home_score' in fields: merge_field(match, "home_score", int(fields['home_score'])) else: merge_field(match, "home_score", 0) if 'away_score' in fields: merge_field(match, "away_score", int(fields['away_score'])) else: merge_field(match, "away_score", 0) if match.state == GameState.COMPLETE: if match.home_score > match.away_score: merge_field(match, "winner", match.home.name) elif match.away_score > match.home_score: merge_field(match, "winner", match.away.name) else: merge_field(match, "winner", "Tied") for i, map_name in enumerate(fields['maps']): winner_home = fields['maps_home'][i] winner_away = fields['maps_away'][i] if winner_home and winner_away: winner = Winner.TIED elif winner_home: winner = Winner.HOME elif winner_away: winner = Winner.AWAY else: winner = Winner.NONE map_obj = Map(map_name, winner) if len(match.maps) < i + 1: match.maps.append(map_obj) match.dirty = True else: if match.maps[i] != map_obj: match.maps[i] = map_obj match.dirty = True
SCALES = [ -79.5, 21.8, 70.225, 80.112, 82.992, 84.15, 84.61, 84.85, 84.972, 85.027, 85.055, 85.065, 85.07, 85.074, 85.077, 85.079, 85.08, 85.0805 ] clock = pygame.time.Clock() running = True pressed = False buttons = pygame.sprite.Group() labels = pygame.sprite.Group() from classes.button import Button from classes.labl import Label from classes.map import Map cur_map = Map() result = Label('', 'black', 10, 60) scheme = Button(' Схема ', 'red', width - 50, height - 390, angle=270) sputnik = Button(' Спутник ', 'blue', width - 50, height - 265, angle=270) hybrid = Button(' Гибрид ', 'green', width - 50, height - 130, angle=270) search = Button( ' Искать ', 'black', width - 90, 5, ) post = Button(' Почтовый индекс ', 'black', width - 470, 50) cancel = Button(' Сброс поискового результата ', 'black', width - 287, 50) text_input = text_input.TextInput(font_family='font.ttf', font_size=30,
0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] """ """ data = [ 0, -1, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0] """ data = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] width = 8 height = 6 start = Point(2, 3) stop = Point(6, 3) map = Map(data, width, height, stop) node = aStar(start, stop, map) while node: print(node.getPoint()) node = node.getParent()
class Game(object): def __init__(self): self._running = True self._fps = 30 self.window_size = (1000, 600) pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() self.screen = pygame.display.set_mode(self.window_size) self.map_surface = pygame.Surface((800, 600)) self.inventory_surface = pygame.Surface((200, 600)) pygame.display.set_caption("Dungeon-RPG") self.clock = pygame.time.Clock() self.map = Map("map.tmx") # Init camera Cam.x = 800/2-self.map.player.x Cam.y = 600/2-self.map.player.y self.font = pygame.font.Font("media/fonts/munro_small.ttf", 22) self.tooltip = None def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self._running = False elif event.type == pygame.USEREVENT: self.tooltip = self.font.render(event.msg, True, (0, 0, 0)) # KEYS elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self._running = False elif event.key == pygame.K_SPACE: self.map.player.attack() # MOUSE elif event.type == pygame.MOUSEBUTTONDOWN: # TODO: Make it short if self.map.player.inventory.collide_inventory(pygame.mouse.get_pos()): self.map.player.inventory.equip(self.map.player.inventory.collide_inventory(pygame.mouse.get_pos())) elif self.map.player.inventory.collide_equipped(pygame.mouse.get_pos()): self.map.player.inventory.unequip(self.map.player.inventory.collide_equipped(pygame.mouse.get_pos())) keys = pygame.key.get_pressed() if keys[pygame.K_a]: self.map.player.move_left() elif keys[pygame.K_d]: self.map.player.move_right() elif keys[pygame.K_w]: self.map.player.move_top() elif keys[pygame.K_s]: self.map.player.move_down() # TODO: Clear it and decide where should be all updates def updates(self): self.map.update() def run(self): while self._running: self.events() self.updates() self.map_surface.fill(((9, 7, 10))) self.inventory_surface.blit(pygame.image.load("media/panel.png"), (0, 0)) # self.screen.fill((9, 7, 10)) self.map.background_tiles.draw(self.map_surface) self.map.collision_tiles.draw(self.map_surface) self.map.items.draw(self.map_surface) self.map.player.inventory.draw(self.inventory_surface) self.map_surface.blit(self.font.render(str(self.clock.get_fps()), True, (255, 255, 255)), (10, 10)) self.inventory_surface.blit(self.font.render("Piniondze: " + str(self.map.player.inventory.gold) + " BTC", True, (255, 255, 255)), (10, 10)) # TODO: Made fast, consider if its good # IDEA: A co gdyby go zawsze rysować, a jego wyglądem sterować z klasy Player? # IDEA: Make animations sprite group? # Draws sword when attacking if self.map.player.attacking: print(self.map.player.sprite_row) # FIXME: Rotating change sprite size. That's why deltas are different delta_x = 0 delta_y = 0 if self.map.player.sprite_row == 1: flip = True delta_x = -24 elif self.map.player.sprite_row == 2: flip = False delta_x = 16 elif self.map.player.sprite_row == 3: flip = True delta_y = -16 elif self.map.player.sprite_row == 0: flip = False delta_y = 32 self.map_surface.blit( pygame.transform.flip(pygame.transform.rotate( self.map.player.inventory.get_equipped_weapon().image, -self.map.player.attacking_time * 8), flip, False), (400 + delta_x, 300 + delta_y)) # Blit tooltip if exists if self.tooltip: self.map_surface.blit(self.tooltip, pygame.mouse.get_pos()) self.tooltip = None self.map_surface.blit(self.map.player.image, (self.map.player.rect.x, self.map.player.rect.y)) self.screen.blit(self.map_surface, (0, 0)) self.screen.blit(self.inventory_surface, (800, 0)) pygame.display.flip() self.clock.tick(self._fps) pygame.quit()
import random from classes.map import Map #Screen/Game Parameters WIDTH = 500 HEIGHT = 500 FPS = 30 # initialize pygame and create window pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Python Tower Defense") gameClock = pygame.time.Clock() # initialize instances of assets gameMap = Map() # game loop running = True while running: # Process input (events) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update # Draw / render gameMap.drawMap(screen)
class Controller(): # X position that player starts level at player_x = PLAYER_X_VAL def __init__(self, game_display, game_screen, screen_dims, colour, clock_delay): # Run game - used to exit game loop self.run = True # Load game settings with open('json/settings.JSON') as settings: self.settings = json.load(settings) # Add important game features to self self.game_display = game_display self.game_screen = game_screen self.screen_dims = screen_dims self.colour = colour self.clock_delay = clock_delay # Setup score and level displays self.score = Score(game_screen) self.level = Level(game_screen) # Setup key distances self.spawn_area = (2 * self.player_x, screen_dims[0]) self.map_width = self.game_screen.get_width() self.mid_width = self.map_width // 2 self.mid_height = self.game_screen.get_height() // 2 self.weapon_types = list(WEAPON_TYPES.keys()) # Setup level complete variables self.level_complete = False self.level_complete_text_1 = Text(self.game_screen, (self.mid_width, self.mid_height - 40), 30, 'Level Complete' ) continue_string = f'Press {self.settings["next_level"]} to continue' self.level_complete_text_2 = Text(self.game_screen, (self.mid_width, self.mid_height), 30, continue_string ) # Setup first level self.firstLevel() # Setup god mode capability - used for debugging self.god_mode = False self.cheats = 0 # Play game music self.playMusic() self.projectiles = pygame.sprite.Group() def playMusic(self): ### Setting up game music # - Music code inspired by code here: # https://riptutorial.com/pygame/example/24563/example-to-add- # music-in-pygame track = TRACKS[self.settings['music']] if track == 'Mute': pygame.mixer.music.stop() else: level_music = MUSIC_LOCATIONS[track] pygame.mixer.music.set_volume(level_music[1]) pygame.mixer.music.load(level_music[0]) pygame.mixer.music.play(-1) def setupCameraMap(self): ''' Sets up camera and map for a given level ''' self.camera = Camera(self.game_screen) self.background = Background(self.game_display) self.game_map = Map(self.game_display, self.screen_dims, 32) def setupPlayer(self): ''' Sets up player for the first level ''' self.player = Player(self.game_display, self.game_map, self.player_x, - 100) self.player_group = pygame.sprite.Group() self.player_group.add(self.player) self.characters = pygame.sprite.Group() self.characters.add(self.player) def addCameraTracking(self): ''' Method to add all blitted objects to camera ''' self.camera.addBack(self.background) self.camera.addMap(self.game_map) self.camera.addPlayer(self.player) for enemy in self.enemy_group: self.camera.add(enemy) def decideEnemyType(self): ''' Randomly returns an enemy from the enemies list Consulted docs below to check how to use randint vs randrange https://docs.python.org/3/library/random.html ''' idx = random.randrange(len(ENEMIES)) return ENEMIES[idx] def decideRandomArm(self): ''' Randomly determine which arms to give an enemy ''' idx = random.randrange(len(self.weapon_types)) return self.weapon_types[idx] def generateLevel(self): ''' This function generates a new level, and enemies to fight ''' # Setup enemy group for level self.enemy_group = pygame.sprite.Group() self.dropped_weapons = pygame.sprite.Group() # Set up enemies for level. Level number represents number of # enemies for n in range(self.level.val): enemy_type = self.decideEnemyType() position = random.randrange(self.spawn_area[0], self.spawn_area[1]) enemy = NPC(self.game_display, self.game_map, position, -100, enemy_type, self.decideRandomArm()) enemy.addTarget(self.player_group) self.enemy_group.add(enemy) self.characters.add(enemy) # Tell player about enemies self.player.addTarget(self.enemy_group) # Setup tracking self.addCameraTracking() def resetPlayer(self): ''' Resets player to start point for new level ''' self.player.changeMap(self.game_map) self.player.center = self.player_x, -100 self.player.updateState('idle', self.player.state[1]) self.player.x_y_moving = False self.player.max_health += 10 self.player.health = self.player.max_health def firstLevel(self): ''' Sets up first level ''' introScreen(self.game_screen, self) self.setupCameraMap() self.setupPlayer() self.generateLevel() def newLevel(self): ''' Function to start a new level Increments the level counter, and adjusts player health ''' self.level.val += 1 self.level_complete = False self.setupCameraMap() self.resetPlayer() self.generateLevel() def keyboardInput(self, event): ''' keyboardInput Called by game loop, and checking events from keyboard, and calling respective functions. Includes functionality to activate 'god mode'. The intention of god mode is for debugging without dying. We initially used the syntax: if event.key == pygame.K_w: self.player.startMove("u") However by browing through the documentation, we discovered that with pygame 2.0.0 there was a new feature: pygame.key.key_code(). We can pass in the string of the key eg "space" for space, or "w" for "w". This allows us to easily produce a human readable JSON containing the keybindings so that the user can change the keybindings to those of their choice. We load this JSON each time we instantiate this class, as the intention is that if we have time between now and submission, we will produce a settings screen to allow the user to graphically change the keybindings to their preference. ''' if event.type == pygame.KEYDOWN: # WASD for up/right/left, q for attack if event.key == pygame.key.key_code(self.settings['up']): self.player.startMove("u") elif event.key == pygame.key.key_code(self.settings['right']): self.player.startMove("r") elif event.key == pygame.key.key_code(self.settings['left']): self.player.startMove("l") elif event.key == pygame.key.key_code(self.settings['attack']): self.player.attack() # When level complete, space to move to next level elif (event.key == pygame.key.key_code(self.settings['next_level']))\ and self.level_complete: self.newLevel() # Escape to pause game elif event.key == pygame.K_ESCAPE: self.player.updateState('idle', self.player.state[1]) self.player.x_y_moving = False pauseScreen(self.game_screen, self) # Enter cheat code to enter god mode elif event.key == pygame.K_RSHIFT: self.cheats = 1 elif (event.key == pygame.K_1) and (self.cheats == 1): self.cheats += 1 elif (event.key == pygame.K_2) and (self.cheats == 2): self.cheats += 1 elif (event.key == pygame.K_3) and (self.cheats == 3): self.cheats += 1 elif event.type == pygame.KEYUP: # Toggle right/left moving if event.key == pygame.key.key_code(self.settings['right']): self.player.stopMoveX("right") elif event.key == pygame.key.key_code(self.settings['left']): self.player.stopMoveX("left") # Lift right shift to submit code for god mode elif event.key == pygame.K_RSHIFT: if self.cheats == 4: self.initGodMode() self.cheats = 0 else: self.cheats = 0 def initGodMode(self): ''' God Mode This is here to debug the game without dying, and without having to edit the code. ''' self.god_mode = True self.player.max_health = 1000000000000000000000000000 self.player.health = self.player.max_health self.gt = Text(self.game_screen, (110, self.game_screen.get_height() - 20), 20, 'god mode activated') self.player.arms.strength *= 10000 def update(self): ''' Update function - Used to update positions of characters on screen. This was initially encapsulated in the display function, however this caused issues when the map functions were tracking characters. This was due to the fact that some changes to the characters position (such as due to gravity and recoil) were being applied after the map had updated. To avoid this, update functions were added to characters. These are called before we blit to the screen. ''' # Updating character positions for character in self.characters: character.update() for projectile in character.thrown_projectiles: # Get any new projectiles and add to camera if not self.projectiles.has(projectile): self.projectiles.add(projectile) self.camera.addWeapon(projectile) # update tracked projectiles for projectile in self.projectiles: # If projectile off screen, remove from sprite groups if (projectile.rect.centerx < 0) or \ (projectile.rect.centerx > self.map_width): projectile.kill() projectile.update() for weapon in self.dropped_weapons: weapon.update() # Check if player is alive if self.player.alive == False: # End game self.run = False gameOver(self.game_screen, self.player.score, self.clock_delay) for enemy in self.enemy_group: if enemy.rect.bottom > self.screen_dims[1]: enemy.kill() if enemy.alive == False: self.camera.addWeapon(enemy.arms) self.dropped_weapons.add(enemy.arms) enemy.arms.addCharacterGroup(self.characters) enemy.kill() if len(self.enemy_group) == 0: self.level_complete = True #self.score_string.text = f'Score = {self.player.score}' self.score.val = self.player.score # Update camera position self.camera.scroll() def display(self): ''' Display This displays all our objects to the screen in order. This takes place each frame. ''' # Colour screen purple self.game_display.fill(self.colour['purple']) # Display background and map self.background.displayQ() self.game_map.display() # Display characters for enemy in self.enemy_group: enemy.display() self.player.display() for weapon in self.dropped_weapons: weapon.display() #print(self.projectiles) for projectile in self.projectiles: projectile.display() # scales the game_display to game_screen. Allows us to scale # images scaled_surf = pygame.transform.scale(self.game_display, self.screen_dims) self.game_screen.blit(scaled_surf, (0, 0)) self.score.display() self.level.display() # If in god mode, display text if self.god_mode: self.gt.display() # If waiting to change level, display text if self.level_complete: self.level_complete_text_1.display() self.level_complete_text_2.display()
'diff': evolve_victor, 'ffb': first_fit_batteries, 'ffh': first_fit_houses, 'gn': find_raced_fit } algorithm = input("Which algorithm do you want to use? ") if algorithm.lower() in algorithm_func: print("Let's go") else: sys.exit( "\nPlease use a good algorithm.\n\nFor hillclimber, choose \tHILL.\nFor differential, choose \tDIFF.\nFor first fit, choose \tFFB or FFH. \nFor genetic race, choose \tGN" ) while len(first_generation) < 4: try: grid = Map(use_map) grid.execute(algorithm_func[algorithm.lower()]) grid.start() if [house.id for house in grid.houses if house.connected is None] == []: print(f"Found a child that costs {grid.moneyspent}!") first_generation.append(grid.get_list()) else: print("Found an insufficient child.") except AttributeError: print("Failed attempt.") grid = Map(use_map) generation = DEGeneration(grid.houses,
def __init__(self, isBot=False): self.isBot = isBot self.map = Map() self.deny_shoots = [] self.target_ships = [] self.kills = 0
class Player: def __init__(self, isBot=False): self.isBot = isBot self.map = Map() self.deny_shoots = [] self.target_ships = [] self.kills = 0 def getMaps(self): return self.map.maps() def getXY(self, cmd=False): if self.isBot: return self.getBotShoot() return self.map.getXY(cmd) def makeShoot(self, x, y, enemyPlayer): if not self.map.isShoot(x, y): return 2 isGoal = enemyPlayer.isGoal(x, y) self.map.saveShoot(x, y, isGoal) enemyPlayer.map.saveEnemyShoot(x, y) if isGoal: self.__setDeny(x, y) self.target_ships.append((x, y)) self.kills += 1 return 1 return 0 def isGoal(self, x, y): if self.map.isShip(x, y): return True return False def getBotShoot(self): while len(self.target_ships) > 0: xg, yg = self.target_ships[0] for i in range(4): x, y = self.__randDirect(xg, yg, i) if self.isRange(x, y): return x, y self.target_ships.pop(0) return self.getRandomShoot() def getRandomShoot(self): while True: x = random.randint(1, 10) y = random.randint(1, 10) if self.isRange(x, y): return x, y def __randDirect(self, x, y, dir): randDirect = [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)] return randDirect[dir] def __setDeny(self, x, y): self.deny_shoots.append(((x + 1), (y + 1))) self.deny_shoots.append(((x + 1), (y - 1))) self.deny_shoots.append(((x - 1), (y + 1))) self.deny_shoots.append(((x - 1), (y - 1))) def isRange(self, x, y): if self.map.isShoot(x, y) and self.map.isMap( x, y) and (x, y) not in self.deny_shoots: return True return False def isWinner(self): if self.kills >= 20: return True return False