def __init__(self, Sound=None): self.spritesheet = Image.SpriteSheet(path="res\\testSheet.png", spriteSize=32) self.OffsetX, self.OffsetY = 0, 0 self.animTiles = [] self.backRendered = False self.playerInputs = Constants.PlayerControls self.Entities = [] super().__init__() self.TileMap, caverns = Mapper.generateCellularAutomata() self.entitypositions = Mapper.placeEnemiesCellular(caverns) for position in self.entitypositions: self.Entities.append( Entities.TestEnemy(x=position[1], y=position[0], Map=self.TileMap)) playerPos = choice(caverns[0]) while playerPos in self.entitypositions: playerPos = choice(caverns[0]) self.player = Entities.Player(x=playerPos[1], y=playerPos[0], map=self.TileMap) self.graph = Pathfinding.Graph(self.TileMap) self.Sound = SoundHandler.Sound() self.Sound.PlayMusic('res/SFX/music.wav') self.offsetScene()
def display_winner(winner, score): """ Display winner of the current match to the users """ # Create the main menu button/text objects txt_title = Entities.Text(title_font, "Congratulations!", Colours.WHITE, width / 2, 38) txt_winner = Entities.Text(main_font, "The winner is " + winner + "!", Colours.WHITE, width / 2, height / 2) btn_return = Entities.Button(main_font, "Return to Main Menu", Colours.WHITE, width / 2, 300) update_highscores(score, winner) while True: # Handle events for e in pygame.event.get(): if e.type == pygame.QUIT: quit_game() # Call the event handler for the button object and do necessary function call if needed display_main_menu() if btn_return.event(e) else False # Draw everything to the screen renderer.update_display(display) renderer.add(txt_title) renderer.add(txt_winner) renderer.add(btn_return) renderer.draw("bg_plain")
def _processRemoving(self): while len(self.entityDelQueue): e = self.entityDelQueue.pop(0) if e in self.groups['all']: self.groups['all'].remove(e) else: # print "was told to delete entity but it was not in the 'all' group: " + repr(e) # DEBUG continue if Entities.isEntityKind_updating(e): self.groups['updating'].remove(e) if Entities.isEntityKind_physics(e): self.space.remove(e.shapes) for shape in e.shapes: del self.spaceView.shapeToEntity[shape] if e.body is not self.space.static_body: self.space.remove(e.body) if Entities.isEntityKind_visible(e): # self.drawLayers[e.drawLayer].remove(e) if hasattr(e, 'draw'): self.drawCalls[e.drawLayer].remove(e.draw) if hasattr(e, 'sprite'): e.sprite.delete() # for vertexList in e.vertexLists: # vertexList.delete() if isinstance(e, Blob): del self.blobs[e.id]
def update_event(self, evt): if evt.type == pygame.KEYDOWN and evt.key == pygame.K_q or evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 1: if self.game.player.use_time < 0: self.game.player.selected_item = 0 self.game.player.use_item() elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_e or evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 3: if self.game.player.use_time < 0: self.game.player.selected_item = 1 self.game.player.use_item() elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_r or evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 2: if self.game.player.use_time < 0: self.game.player.selected_item = 2 self.game.player.use_item() elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_f: if self.game.player.bombs > 0: self.game.player.bombs -= 1 self.game.room.entities.append(Entities.Bomb(self.game.room, pygame.math.Vector2(self.game.player.pos[0] + 16, self.game.player.pos[1] + 16))) elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_SPACE: self.game.player.interact() # Created by Gregory Moncayo elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_v: dropped_item = Entities.ItemPickup(self.game.room, self.game.player.inventory[0]) dropped_item.pos = pygame.math.Vector2(self.game.player.pos[0] + 16, self.game.player.pos[1] + 16) self.game.room.entities.append(dropped_item) self.game.player.inventory[0] = None
def create_move_to_message(company_num, field_object_id, new_location): message = Entities.MoveOrderMessage(company_num, field_object_id, new_location) packet = Entities.Packet(Sender.company_commander.value, company_num, Receiver.soldier.value, MessageType.move_order.value, message) return packet
def render(Plot): global screen, background screen.fill((255, 255, 255)) #black #screen.blit(background, (0,0))#load backgroud #for tile in tileMap:#load map first # screen.blit(tile.sprite, (tile.x, tile.y), tile.frame) #for row in range(Map.MAPHEIGHT): # for column in range(Map.MAPWIDTH): # screen.blit(Map.tiles[Map.tilemap[row][column]], (column * Map.TILESIZE, row * Map.TILESIZE)) Map.displayMap(Plot.currentRoom(), screen) displaySprite(Plot.currentRoom()) for entitiy in sprites: #load entities screen.blit(entitiy.sprite, ((entitiy.x, entitiy.y)), entitiy.frame) #IF textbox load textbox michael.drawTextBox(screen) michael.drawText(Plot.currentText(), screen) #if textbox: #print("There is a text box!") Entities.displayArrow(screen, Plot.currentState, Plot.decision) pygame.display.flip() #print to screen
def mouse_rightdrag(start, stop): color = random_color() size = start - stop size = int(size.length()) if size < 10: size = 10 Entities.spawn_rectangle(start, size, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color, mod=Entities.Object.MOVABLE)
def display_rules(return_to=None): """ Display the game rules to the users """ str_rules = \ "Each player has 2 counters, the objective is for a player to get \n" \ "each of their counters to the FINISH space before the other player.\n" \ "The game uses a 5 sided dice. The result a dice throw is as follows:" str_die_results = \ "+-----------+----------------------------------------------------+\n" \ "| Dice Roll | Action |\n" \ "+-----------+----------------------------------------------------+\n" \ "| 1 | Move a counter of choice 1 space closer to FINISH |\n" \ "+-----------+----------------------------------------------------+\n" \ "| 2 | Move a counter of choice 2 spaces closer to FINISH |\n" \ "+-----------+----------------------------------------------------+\n" \ "| 3 | Move a counter of choice 3 spaces closer to FINISH |\n" \ "+-----------+----------------------------------------------------+\n" \ "| 4 | Move a counter of choice 1 space closer to START |\n" \ "+-----------+----------------------------------------------------+\n" \ "| 5 | Select a counter to move to the next EMPTY row |\n" \ "+-----------+----------------------------------------------------+" # Create the main menu button/text objects txt_rules_title = Entities.Text(title_font, "Rules", Colours.WHITE, width / 2, 38) txt_goal = Entities.Text(small_font, str_rules, Colours.WHITE, width / 2, 100) txt_die_results = Entities.Text(small_font, str_die_results, Colours.WHITE, width / 2, 150) btn_return = Entities.Button( main_font, "Return to " + ("Main Menu" if return_to is "main" else "Game"), Colours.WHITE, width / 2, 300) while True: # Handle events for e in pygame.event.get(): if e.type == pygame.QUIT: quit_game() # Call the event handler for the button object and do necessary function call if needed if return_to is "main" and btn_return.event(e): display_main_menu() elif return_to == "play" and btn_return.event(e): return # Draw everything to the screen renderer.update_display(display) renderer.add(txt_rules_title) renderer.add(txt_goal) renderer.add(txt_die_results) renderer.add(btn_return) renderer.draw("bg_plain")
def mouse_rightdrag(self, start, stop): color = random_color() start = Physics.Vec2(start[0], start[1]) stop = Physics.Vec2(stop[0], stop[1]) size = start - stop size = int(size.length()) if size < 10: size = 10 Entities.spawn_rectangle(start, size, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color) pygame.draw.rect(self.screen, color, Rect(start.x, start.y, size, size))
def mouse_leftdrag(self, start, stop): color = random_color() start = Physics.Vec2(start[0], start[1]) stop = Physics.Vec2(stop[0], stop[1]) size = start - stop size = int(size.length()) if size < 10: size = 10 Entities.spawn_ball(start, size, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color) pygame.draw.circle(self.screen, color, (int(start.x), int(start.y)), size, 0)
def draw_blocks(self): colour_list = ["red", "yellow", "green", "blue", "purple"] y_coord = 40 start_x = 10 for colour in colour_list: for i in range(0, 12): self.block_list.append(Entities.Block(start_x + 65 * i, y_coord, colour)) y_coord += 20 for i in range(0, 12): self.block_list.append(Entities.Block(start_x + 65 * i, y_coord, colour)) y_coord += 20
def deal_cards(self): for i, j in self.board.card_noPlaced(): self.board.set_status_true(i, j) card_image = self.deck.deal_cards() #If we had a image card returned then assign it to a card object. if card_image: card = ent.card(card_image, self.board.card_positions[i][j][0]) self.window.deal_animation(card.position, ent.deck([640, 190])) self.window.sprites_list.add(card) else: print("No more cards") print("cards left: " + str(self.deck.get_numCards()))
def display_enter_player_names(): """ Ask the users to enter their names """ # Create the menu button/text/field objects txt_title = Entities.Text(title_font, "Enter Player Names", Colours.WHITE, width / 2, 38) txt_user = Entities.Text(main_font, "Player 1, enter your name:", Colours.WHITE, width / 2, 150) txt_hint = Entities.Text(main_font, "Enter name (press enter to set)", Colours.WHITE, width / 2, 380) name_field = Entities.InputField(main_font, "Player 1", Colours.BLACK, width / 2, 200, 14) btn_return = Entities.Button(main_font, "Return to Main Menu", Colours.WHITE, width / 2, 300) player = 1 player_names = ["Player 1", "Player 2"] while True: # Handle events events = pygame.event.get() for e in events: if e.type == pygame.QUIT: quit_game() # Call the event handler for the button object and do necessary function call if needed if btn_return.event(e): display_main_menu() if name_field.event(e): field_text = name_field.get_text() if field_text: player_names[player - 1] = field_text player += 1 name_field.reset("Player 2") txt_user.update_text("Player 2, enter your name:") # Draw everything to the screen renderer.update_display(display) renderer.add(txt_title) renderer.add(txt_user) renderer.add(name_field) renderer.add(btn_return) renderer.add(txt_hint) renderer.draw("bg_plain", Colours.BLACK) if player > 2: return player_names
def update(self, world): if not self.time: p = world.get_p(self.x, self.y) if p.x < self.x: world.e.append(Entities.CannonBall(self.x, self.y, -1)) shot.play() elif p.x > self.x: world.e.append(Entities.CannonBall(self.x, self.y, 1)) shot.play() self.time = randint(120, 360) else: self.time -= 1
def mouse_ctrlclick(start, mouse_pos): """ #create line with random angle #use unit vector with scalar and a starting point #u = v/||v|| random angle could maby be found with using formula for angle of vectors with dotproducts where one of the vectors could be the x axis |v|*|w|*cos(theta) #will need an angle in gradients to be able to paint """ color = (0, 0, 0) direction_vector = mouse_pos - start length = math.sqrt(direction_vector.x**2 + direction_vector.y**2) Entities.spawn_line(start, direction_vector, length, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color, direction_vector.angle())
def start_game(self): self.loading_screen() self.map = MapGenerator.Map(self.settings['map_size']) self.Player = Entities.Player( (int(self.settings['window_size'][0] / 2), int(self.settings['window_size'][1] / 2), 180), self.settings['map_size']) self.entities = self.create_entities() self.projectiles = [] self.Camera = Entities.Camera(self.Player, self.settings['window_size'], self.map) self.score = 0 self.game_loop()
def create_entities(self): entities = [] for i in range(self.settings['number_of_enemies']): x = random.randint(0, self.settings['map_size'][0]) y = random.randint(0, self.settings['map_size'][1]) angle = random.randint(0, 359) aircraft = random.choice(['Mig21', 'Mig35']) if aircraft == 'Mig21': entities.append( Entities.Mig21((x, y, angle), self.settings['map_size'])) elif aircraft == 'Mig35': entities.append( Entities.Mig35((x, y, angle), self.settings['map_size'])) return entities
def mouse_ctrlclick(self, mouse_pos): """ #create line with random angle #use unit vector with scalar and a starting point #u = v/||v|| random angle could maby be found with using formula for angle of vectors with dotproducts where one of the vectors could be the x axis |v|*|w|*cos(theta) #will need an angle in gradients to be able to paint """ length = random.randint(1, 200) color = (0, 0, 0) angle = random.randint(0, 180) direction_vector = Physics.Vec2(math.sin(angle)*length, math.cos(angle)*length) start = Physics.Vec2(mouse_pos[0], mouse_pos[1]) Entities.spawn_line(start, direction_vector, length, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color, angle)
def random_event(): x = random.randint(0, 50) if x in [0, 1]: print("\nThe grinding sound of metal gears unexpectedly catches your attention...") enemy = Entities.BasicEnemy(name='Drone', target=player) if random.randint(0, 1) < 1 == True: weapon = Items.Weapon(*Items.basic_primary_weapons[random.randint(0, len(Items.basic_primary_weapons) - 1)]) enemy.equip_primary_weapon(weapon) active_enemies.append(enemy) time.sleep(2) print(f"You've wandered into a hidden {enemy.name}!") time.sleep(1) enemy.combat_turn() enemy_encounter(player, enemy) # elif x == 3: # print() # print("You happen upon some edible berries on the side of the road!") # print("\tYour health is increased by 1!") # time.sleep(2) # player_health += 1 # elif x == 4: # print() # print("An angry squirrel bites you on the ankle!") # print("\tYour health is decreased by 1!") # player_health -= 1 # time.sleep(2) else: return
def on_pick_enemy(self, event): self.status.setText("") this_point = event.artist # x_data and y_data of the point that was picked by the user x_data = this_point.get_xdata() y_data = this_point.get_ydata() for enemy in self.enemies: if enemy.x == x_data and enemy.y == y_data: self.picked_enemy.append(enemy) break self.engage_pushButton.setDown(False) for soldier in self.picked_soldier: message = Entities.EngageOrderMessage(soldier, enemy) packet = Packet(Sender.company_commander.value, self.company_commander.company_number, Receiver.soldier.value, MessageType.engage_order.value, message) send_handler(packet) time.sleep(0.1) self.picked_soldier.clear() self.picked_enemy.clear() self.move_pushButton.setEnabled(False) self.engage_pushButton.setEnabled(False) self.cancelButton.setEnabled(False) self.MplWidget.canvas.mpl_connect("pick_event", self.on_pick) self.MplWidget.canvas.mpl_disconnect(self.MplWidget.canvas.mpl_connect('pick_event', self.on_pick_enemy))
def use(self, char): Debug.print("Used bow") angle = math.atan2(char.pos.x - pygame.mouse.get_pos()[0], char.pos.y - pygame.mouse.get_pos()[1]) bullet = Entities.Bullet(char.room, -angle - 3.14 / 2, 2, False) bullet.pos = pygame.math.Vector2(char.pos.x + 12, char.pos.y + 12) char.room.entities.append(bullet)
class Question: #DB Entity for this wrapper internalData = Entities.Question() #Returns Id of question. def __init__(self, id): self.internalData = DbConnection.session.query(Entities.Question).filter(Entities.Question.id == id).first() if self.internalData == None: raise ValueError def id(self): return self.internalData.id #Return question text of this question. def question(self): return self.internalData.question #Return answer text of this question. def answer(self): return self.internalData.answer #Make a guess with the user provided. def guess(self, user, answer): return #TODO #Provide the hint text to the user provided def hint(self, user): return #TODO #Create a new question and save it to database. @staticmethod def Create(id, question, answer, hint, image): newQuestion = Entities.Question() newQuestion.id = id newQuestion.question = question newQuestion.answer = answer newQuestion.hint = hint newQuestion.image = image DbConnection.session.add(newQuestion) DbConnection.session.commit() #TODO kéne tudni hogy sikeres volt-e! Commit dob vissza ilyet? return True @staticmethod def Delete(id): entity = DbConnection.session.query(Entities.Question).get(id); if(entity != None and entity.id != None) DbConnection.session.delete(entity) DbConnection.session.commit() #Get all questions currently stored in the database. Returns List<Question> @staticmethod def All(): result = [] entities = DbConnection.session.query(Entities.Question).all() for entity in entities: result.append(Question(entity.id)) return result
def load_map(): # TODO add gui to allow easy pickings # TODO use pickle with grid global entity_index global game_grid filename = "maps/gridfile2018-06-23 11:07:29.768659.txt" with open(filename, 'r') as level_file: for line in level_file: (col, row) = tuple(map(int, line.replace('\n', '').split(" "))) game_grid[row][col] = 1 block = e.Block(entity_index, col * v.block_size, row * v.block_size) e.group.add(block) entity_index += 1 game_grid = np.pad(game_grid, pad_width=v.padding, mode='constant', constant_values=-1) e.initgrid(game_grid)
def __init__(self, game): super().__init__(game) self.dead_timer = 0 self.game.player.room = self.game.room self.game.room.entities.append(self.game.player) self.heart_tex = pygame.image.load("res/ui/hearts.png").convert_alpha() self.bomb_tex = pygame.image.load("res/ui/bomb.png").convert_alpha() self.gold_tex = pygame.image.load("res/ui/gold.png").convert_alpha() self.room_icons_tex = pygame.image.load("res/ui/room_icons.png").convert_alpha() self.label_font = pygame.font.SysFont("Consolas", 12) self.large_font = pygame.font.SysFont("Consolas", 20) Entities.fix_textures()
def call(username): print('Welcome Moderator to the discussion forum!!') #username = input('Please enter your user name: ') choice1 = int(input('1. Create a forum 2. Drop a forum')) business_logic = DiscussionForumLogic.DiscussionForumLogic() if choice1 == 1: forumid = int(input('Give a unique forum id to your forum: ')) topic = input('What would be its topic: ') url = input('Enter URL') summary = input('Summarise your topic: ') whencreated = datetime.datetime.now() whenclosed = None createdbymoderator_username = username deletedbymoderator_username = None forum_object = Entities.Forum(forumid, topic, url, summary, whencreated, whenclosed, createdbymoderator_username, deletedbymoderator_username) forum_created = business_logic.create_forum(forum_object) if forum_created: print('Forum Created!!') else: print( 'Either moderator does not exist or forum id is not unique!!') elif choice1 == 2: forumid = int( input('Enter the forum id you want to remove from system: ')) forum_removed = business_logic.remove_forum(forumid, username) if forum_removed: print('Forum is removed!!') else: print('Either moderator or forum id does not exist!!')
def __init__(self): self.seed = random.randint( 0, 765867586578 ) #will have a random seed that is used to generate the worlds in a deterministic way self.score = 0 self.floor = 0 self.name = "Solid Snake" self.level = getValue('GameState', 'level', 'str') #random seed for genration or actual name self.world = WorldGrid.WorldGrid(self) #is a worldgrid object self.newseed = getValue( 'GameState', 'seed', 'int' ) #will have a random seed that is used to generate the worlds in a deterministic way self.hero = Entities.Hero(getValue('Entities', 'heroMove', 'int'), getValue('Entities', 'heroName', 'str')) self.monsters = [] self.exit = Entities.Exit()
def __init__(self): self._log = getLogger('pymygw') self._engine = create_engine(config.Database, #echo=True, connect_args={'check_same_thread': False}, poolclass=StaticPool) self._schema = Entities.getSchema(self._engine) self._dbsession = scoped_session(sessionmaker(bind=self._engine))
def __init__(self, start_time): pygame.key.set_repeat() # Stores 1 dimensional list of each block self.block_list = [] self.width = pygame.display.Info().current_w self.height = pygame.display.Info().current_h self.start_time = start_time self.font = pygame.font.Font("8bitfont.ttf", 25) self.large_font = pygame.font.Font("8bitfont.ttf", 60) self.game_over_text = pygame.image.load("images/gameover.png").convert_alpha() self.game_over_state = False self.victory_state = False self.buttons = {} self.buttons['Main Menu'] = Gui.StandardButton((400, 350, 60, 30), 'Main Menu', center_x=True, font_size=40) self.buttons['Main Menu'].visible = False self.buttons['Leaderboards'] = Gui.StandardButton((400, 420, 60, 30), 'Add to leaderboards', center_x=True, font_size=40) self.buttons['Leaderboards'].visible = False # Draw all the blocks on the screen self.draw_blocks() self.lives = 3 self.score = 0 # Initialises the Paddle and ball classes ready to use in the game self.paddle = Entities.Paddle() self.ball = Entities.Ball(self.paddle.rect.x + self.paddle.rect.width / 2 - 10, self.paddle.rect.y - 20) # Load audio self.block_hit_sound = pygame.mixer.Sound("sounds/hit.wav") self.game_over_sound = pygame.mixer.Sound("sounds/game_over.wav") self.gametime = 0 self.time_in_play_store = 0 self.time_in_play = 0 self.gold_block_exists = False self.time_store = 0 self.running = False self.new_game = True self.speed_up_1 = False self.speed_up_2 = False # Is also a subclass of Scene so it needs to be initialized super().__init__()
def Create(name): newGroup = Entities.Group() newGroup.name = name DbConnection.session.add(newGroup) DbConnection.session.commit() #TODO kéne tudni hogy sikeres volt-e! Commit dob vissza ilyet? return True
def explode(self, x, y, p): if self.inworld(x, y): if self.o[x][y]: if self.o[x][y].destructible: self.o[x][y] = None self.e.append(Entities.Explosion(x, y, p)) else: self.o[x][y].explode(self) return True if not p: return True else: self.e.append(Entities.Explosion(x, y, p)) gent = self.get_ent(x, y) if gent and gent.name == "Bomb": gent.timer = 1 else: return True
def displaySprite(mapNum): player = Entities.Player() king = Entities.King() vizzi = Entities.Vizzi() charles = Entities.Charles() dragon = Entities.Dragon() wizard = Entities.Wizard() villain = Entities.Villain() if mapNum == 0: player.x = (40 * 4) player.y = (40 * 2) - 15 remove(player) add(player) # //player sprite king.x = (40 * 9) king.y = (40 * 2) - 15 remove(king) add(king) elif mapNum == 1: #remove(king) #// Can't seem to get this function to work king.y += 1000 #// Moving them off-screen instead of removing them vizzi.x = (40 * 9) vizzi.y = (40 * 2) - 15 remove(vizzi) add(vizzi) elif mapNum == 2: #remove(vizzi) vizzi.y += 1000 charles.x = (40 * 9) charles.y = (40 * 2) - 15 remove(charles) add(charles) elif mapNum == 3: #remove(charles) charles.y += 1000 dragon.x = (40 * 9) dragon.y = (40 * 2) - 15 remove(dragon) add(dragon) elif mapNum == 4: #remove(dragon) dragon.y += 1000 wizard.x = (40 * 9) wizard.y = (40 * 2) - 15 remove(wizard) add(wizard) elif mapNum == 5: #remove(wizard) wizard.y += 1000 villain.x = (40 * 9) villain.y = (40 * 2) - 15 remove(villain) add(villain) elif mapNum >= 6: #remove(wizard) wizard.y += 1000 villain.x = (40 * 9) villain.y = (40 * 2) - 15 remove(villain) add(villain)
def __init__(self): self.selectedCardCounter = 0 self.selectedCardsList = [] #We create an instance of each of the entities self.window = ent.window() self.deck_position = [640, 190] self.deck = ent.deck(self.deck_position) self.deck2_position = [640, 540] self.deck2 = ent.deck(self.deck2_position) self.board = ent.board() #We add the deck grapichs to the draw list self.window.sprites_list.add(self.deck) #And we update the screen self.window.update() #This list will be filled with the cards that has to be drag from the board self.drag_cards_list = [] #This part deal 12 cards to populate the board. Each of the card has a deck deal animation and also creates a instance for each card and it adds them to draw list self.deal_cards() self.window.update()
def add_sprites(): #TODO Add algorithm to drop in open spaces in any map for i in range(v.player_num): [row, col] = get_space() # print(row) # print(col) players.append(e.Player(i+2, row, col, brains[i])) e.group.add_sprite(players)
def Create(name, passwordHash): newUser = Entities.User() newUser.name = name newUser.password = passwordHash DbConnection.session.add(newUser) DbConnection.session.commit() #TODO kéne tudni hogy sikeres volt-e! Commit dob vissza ilyet? return True
def populateMoles(self): for r in range(len(self.grid)): for c in range(len(self.grid[0])): if self.grid[r][c] == 0: rand = random.randint(0, self.challenge) rare = random.randint(0, 5) if rand == 0: self.challenge = self.difficulty if not rare == 0: mole = Entities.Mole(0, 0) else: mole = Entities.RareMole(0, 0) #places them nicely so they don't overlap mole.x = (c * mole.sprite.get_width()) + self.offset mole.y = (r * mole.sprite.get_height()) + self.offset self.grid[r][c] = 1 self.entities.append(mole) else: self.challenge -= 1
def __init__(self, n_agents=1, with_finish_zone=True, synchronized_activation=True, dampening=0.75): self.n_agents = n_agents self.n = n_agents """ Environment configuration """ self.with_finish_zone = with_finish_zone self.synchronized_activation = synchronized_activation self.dampeding = dampening """ Build required entities """ self.agents = [Entities.Agent() for _ in range(self.n_agents)] self.landmarks = [Entities.Landmark() for _ in range(self.n_agents)] """ Build per agent action space """ self.action_space = [gym.spaces.Box(-1.0, 1.0, (2,)) for _ in range(self.n_agents)] """ 2 : agent position 2 : agent velocity 2 * (n_agents - 1) : relative position to other agents 2 * n_agents : relative position to landmarks n_agents : landmark flags """ obs_dim = 2 + 2 + 2 * (n_agents - 1) + 2 * n_agents + n_agents """ If we are using finish zones : 2 : relative position to finish zone 1 : finish zone radius """ if with_finish_zone: obs_dim = obs_dim + 2 + 1 self.finish_zone = Entities.FinishZone() """ Build per agent observation space """ self.observation_space = [gym.spaces.Box(low=0, high=0, shape=(obs_dim,)) for _ in range(self.n_agents)] self.render_geoms = None self.render_geoms_xform = None self.viewer = None self.rebuild_geoms = False
def createMap(self, x, y): self.grid = [[Tile.Tile('White') for _ in range(y)] for _ in range(x)] self.width = x self.height = y # Create a base from LevelGenerator base = create_level(x, y) # Fill the game grid with entities corresponding to entries in the base for i in range(len(base[0])): for j in range(len(base)): if base[i][j] == 1: self.placeEntity(i, j, Entities.Wall())
def _processAdding(self): while len(self.entityAddQueue): e = self.entityAddQueue.pop(0) self.groups["all"].add(e) if Entities.isEntityKind_updating(e): self.groups['updating'].add(e) if Entities.isEntityKind_physics(e): self.space.add(e.shapes) for shape in e.shapes: self.spaceView.shapeToEntity[shape] = e if e.body is not self.space.static_body: self.space.add(e.body) if Entities.isEntityKind_visible(e): if hasattr(e, 'initGraphics'): e.initGraphics(self.drawLayers[e.drawLayer]) if hasattr(e, 'draw'): self.drawCalls[e.drawLayer].append(e.draw) if isinstance(e, Blob): self.highestBlobId += 1 e.controller = e.controller(e, self.blobs, self.spaceView) # initialize the controller e.id = self.highestBlobId self.blobs[e.id] = e
def remove(): try: director = load_director() group_id = request.form['group_id'] decoded = entities.decode_marathon_id(group_id) service = decoded['service'] labels = str(sorted(decoded['labels'])) group = director.services.get(service).labeled_groups.get(labels) group.undeploy() director.dump() return jsonify(result={"status": 200}) except Exception as failure: print failure return jsonify(result={"status": 500})
def add_group(): try: director = load_director() group_id = request.form['group_id'] delta = int(request.form['delta']) decoded = entities.decode_marathon_id(group_id) service = decoded['service'] labels = str(sorted(decoded['labels'])) group = director.services.get(service).labeled_groups.get(labels) # # scale up this grouop # group.scale(delta) director.dump() return jsonify(result={"status": 200}) except Exception as failure: print failure return jsonify(result={"status": 500})
def mouse_rightclick(self, pos): color = random_color() Entities.spawn_rectangle(Physics.Vec2(pos[0], pos[1]), self.object_size, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color) pygame.draw.rect(self.screen, color, Rect(pos[0], pos[1], self.object_size, self.object_size))
def mouse_leftclick(pos): color = random_color() Entities.spawn_ball(pos, 10, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 100000, color, mod=Entities.Object.MOVABLE)
def mouse_rightclick(pos): color = random_color() Entities.spawn_rectangle(pos, 10, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color, mod=Entities.Object.MOVABLE)
def init(): start = Physics.Vec2(0, (window.height/5)*4) stop = Physics.Vec2(window.width, (window.height/5)*4) dir = stop - start Entities.spawn_line(start, dir, dir.length(), Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, None, dir.angle(), mod=Entities.Object.FIXED)
Globals.player.can_attack = False Globals.player.xvel = 0 elif Globals.player.can_attack == False and Globals.player.attack == 'teabag': Globals.player.attacking = False Globals.player.arrowkey_enabled = True Globals.player.can_attack = True elif event.key == pygame.K_RETURN: for item in Globals.group_EVENTS: if item.waiting_for_proceed == True: item.waiting_for_proceed = False item.next_event() elif event.key == pygame.K_HOME: Globals.player.yvel = -12 elif event.key == pygame.K_ESCAPE: done = True #exit the game if player presses escape elif event.key == pygame.K_F1: block = Entities.damage_tile(pygame.mouse.get_pos()[0] + Globals.camera.x, pygame.mouse.get_pos()[1] + Globals.camera.y) elif event.key == pygame.K_F12: coin = Entities.Coin(pygame.mouse.get_pos()[0] + Globals.camera.x, pygame.mouse.get_pos()[1] + Globals.camera.y) elif event.key == pygame.K_F11: Globals.player.yvel = 0 if Globals.player.gravity: Globals.player.gravity = False else: Globals.player.gravity = True elif event.key == pygame.K_n: next_level() elif event.type == MOUSEBUTTONDOWN: mousex, mousey = event.pos print "Mouse: " + str((mousex + Globals.camera.x, mousey + Globals.camera.y)) #movement if not Globals.menu: if keypressed[K_LEFT] and not Globals.player.keys['right'] == True: Globals.player.left_pressed()
def mouse_leftclick(self, pos): color = random_color() Entities.spawn_ball(Physics.Vec2(pos[0], pos[1]), self.object_size, Physics.Vec2(0, 0), Physics.Vec2(0, 0), 10, color) pygame.draw.circle(self.screen, color, pos, self.object_size, 0)