def main(): Graphics.init(Size(1280, 720)) Time.init() line = GameObject() line.add_component(LineRenderer(Vector2(0, 0), Vector2(10, 10))) fps = GameObject() text = fps.add_component(Text) # game loop while True: # check for events for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() update() text.text = str(int(Time.time)) text.transform.position = text.transform.position + Vector2(1, 0) Graphics.draw()
def main(): libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False) con = libtcod.console_new(screen_width, screen_height) dialog_prompt = DialogPrompt(dialog_pos_x, dialog_pos_y, "npc_dialog", dialog_width, dialog_height, con) game_map = GameMap(map_width, map_height) game_map.switch_map(0) fov_recomputer = True game_entities = [] dialog_entities = [] player = GameObject(3, 3, '@', libtcod.white, "Hero", True) npc = GameObject(int(screen_width / 2 - 5), int(screen_height / 2), '@', libtcod.yellow, "Bad Guy", True) game_entities.append(player) game_entities.append(npc) key= libtcod.Key() mouse = libtcod.Mouse() libtcod.console_set_window_title(game_title+ " - " + game_map.map_name) while not libtcod.console_is_window_closed(): libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse) draw_all(con, game_entities, game_map, screen_width, screen_height) libtcod.console_flush() clear_all(con, game_entities) if key.c == ord('a'): dialog_prompt.npc_dialog('main') action = handle_keys(key) move = action.get('move') exit = action.get('exit') if move: dx, dy = move if not game_map.is_blocked(player.x + dx, player.y + dy) and not game_map.is_transport(player.x + dx, player.y + dy): game_map.unblock(player.x, player.y) player.move(dx,dy) elif game_map.is_transport(player.x + dx, player.y + dy): transport = game_map.spaces[player.x + dx][player.y + dy].transport game_map.switch_map(transport.new_map_index) libtcod.console_set_window_title( game_title + " - " + game_map.map_name) game_map.unblock(player.x, player.y) player.move(dx , dy ) player.move(transport.dx, transport.dy) if key.vk == libtcod.KEY_ESCAPE: return True game_map.update_blocked(game_entities)
def populate(self): player = GameObject(400, 225) player.add_behaviour(PlayerController()) player.add_behaviour(SquareRenderer()) self.game_objects.append(player) for i in range(8): obstacle = GameObject(0, 0) obstacle.x = i * 100 + 50 obstacle.y = i * 50 obstacle.add_behaviour(Movement()) obstacle.add_behaviour(CircleRenderer()) self.game_objects.append(obstacle)
def scene1(): scene = Scene() obj = GameObject('0') obj.load_mesh('../data/deer.obj') obj.set_scale(1 / 30) obj.translate_x(10) obj.rotate_y(-35) scene.objects += [obj] obj = GameObject('1') obj.load_mesh('../data/cube.obj') obj.set_scale(100) obj.translate_x(-50) obj.translate_y(-100) obj.translate_z(-50) scene.objects += [obj] obj = GameObject('2') obj.load_mesh('../data/camero.obj') obj.load_texture('../data/camero.png', 64) obj.set_scale(10) obj.translate_x(-20) obj.translate_z(8) obj.rotate_y(-45) scene.objects += [obj] scene.light = Light() scene.light.shadow_map_dim = 64 scene.light.shadow_map_bias = 1 scene.light.translate_z(1000) scene.light.translate_y(1500) scene.light.translate_x(2000) scene.light.rotate_y(100) scene.light.rotate_x(35) image_width = 320 image_height = 240 scene.camera = Camera(0.98, 0.735, image_width, image_height, 1, 10000, 20, np.eye(4)) scene.camera.translate_y(60) scene.camera.translate_z(60) scene.camera.rotate_x(35) print(scene.camera.world_to_camera) return scene
def __init__(self, size=(1280, 720), fullscreen=False): pygame.init() self.size = size if fullscreen: self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode(size) self.clock = pygame.time.Clock() # Initialize players self.players = pygame.sprite.Group() self.platform_group = pygame.sprite.Group() platform_dimensions = (400, 50) platform_position = (500 - int(platform_dimensions[0] / 2), 600) player_one_dimensions = (100, 150) player_two_dimensions = (100, 200) player_one_position = (platform_position[0], platform_position[1] - int(player_one_dimensions[1])) player_two_position = (platform_position[0] + platform_dimensions[0] - player_two_dimensions[0], platform_position[1] - int(player_two_dimensions[1])) player_one_controls = {'left': pygame.K_LEFT, 'right': pygame.K_RIGHT} player_two_controls = {'left': pygame.K_j, 'right': pygame.K_k} self.player_one = Player(player_one_position, player_one_dimensions, self.size, player_one_controls) self.player_two = Player(player_two_position, player_two_dimensions, self.size, player_two_controls) self.players.add(self.player_one) self.players.add(self.player_two) self.levels = {'Level_01': Level_01(size)} self.platform = GameObject(platform_position, platform_dimensions, self.size) self.platform_group.add(self.platform) self.FPS = 60
def createObject(self, physics=None, renderable=None): gameObject = GameObject(game=self, physics=physics, renderable=renderable) self.gameObjects.append(gameObject) return gameObject
def scene2(): scene = Scene() obj = GameObject('0') obj.load_mesh('../data/camero.obj') obj.load_texture('../data/camero.png', 256) obj.set_scale(20) obj.rotate_y(-45) scene.objects += [obj] scene.light = Light() scene.light.shadow_map_dim = 512 scene.light.shadow_map_bias = 1 scene.light.translate_z(1000) scene.light.translate_y(1500) scene.light.translate_x(2000) scene.light.rotate_y(100) scene.light.rotate_x(45) image_width = 640 image_height = 480 scene.camera = Camera(0.98, 0.735, image_width, image_height, 1, 10000, 20, np.eye(4)) scene.camera.translate_y(40) scene.camera.translate_z(60) scene.camera.rotate_x(35) return scene
def __init__(self): self.is_running = True self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(Constants.SIZE, Constants.FLAGS) self.player = GameObject() self.player.velocity.x = 0.001 pygame.init()
def __init_level__(self, level): path = 'Levels/level_' + str(level) + '.txt' file = open(path, 'r') data = file.read().split('\n') y = 0 counter = 0 for string in data: x = 0 for char in string: if char in ENEMYS: counter += 1 if counter in [20, 15, 10, 5]: self.all_enemys.append(EnemyTank(char, True)) else: self.all_enemys.append(EnemyTank(char)) if char in TILES: type = TILE_TO_TYPE[char] obj = GameObject(type[0], QPoint( x, y), BLOCK_SIZE, BLOCK_SIZE, type[1], type[2]) self.objects.append(obj) x += BLOCK_SIZE y += BLOCK_SIZE file.close()
def create_object(self, position, size, kind): obj = GameObject(position, size, kind, self.next_id) self.next_id += 1 self.game_objects[obj.id] = obj # send event pub.sendMessage('create', game_object=obj) return obj
def spawn_game_object(self, x, y, id=None, prototype=None, **kwargs): object = GameObject(x, y, id=id, prototype=prototype, **kwargs) self.objects.append(object) print("Spawned object w id " + object.id) return object.id
def test_moveable_obj_overlap_break(): tank = EnemyTank('5') brick = GameObject('BRICK', QPoint(0, 0), 32, 32, 1, True) scene.addItem(brick) scene.map.objects.append(brick) length = len(scene.items()) tank.processing_overlap(scene, brick) assert length > len(scene.items())
def _build_order(self, position): order_coordinates = [51, 253, 455, 657, 859, 1061] order_width = 121 order_y = 122 order_height = 29 order_box = (order_coordinates[position], order_y, order_coordinates[position] + order_width, order_y + order_height) order = GameObject('Order Bubble', boundingBox=order_box) return order
def addRoom(self, room): x, y = room.center() room.caption = GameObject(x, y, chr(65 + len(self.rooms)), tcod.white) self.rooms.append(room) #go through the tiles in the rectangle and make them passable for x in range(room.x1 + 1, room.x2): for y in range(room.y1 + 1, room.y2): self.data[x][y].blocked = False self.data[x][y].block_sight = False
def create_player(self): # Create the initial players starting_room = self.map.rooms[tcod.random_get_int( 0, 0, len(self.map.rooms) - 1)] return GameObject(x=starting_room.center().x, y=starting_room.center().y, char='@', color=tcod.white, map=self.map, type='PLAYER')
def spawn_food(self): """Spawn new piece of food for the snake on the board""" range_x, range_y = range(self.width), range(self.height) e = self.EMPTY free = [(x, y) for x in range_x for y in range_y if self.fields[y][x] == e] # If the border was big enough, we could randomize field and then check # if it's occupied - would be faster then, but what about a case when # the snake is so big that it's on a significant part of the board? field = random.choice(free) # f = Food(self, field) f = GameObject(self, char='F', color='g', fields=[field])
def _build_happiness(self, position): happiness_coordinates = [100, 302, 504, 706, 908, 1110] happiness_width = 11 happiness_y = 216 happiness_height = 7 happiness_box = (happiness_coordinates[position], happiness_y, happiness_coordinates[position] + happiness_width, happiness_y + happiness_height) happiness = GameObject('Happiness Indicator', boundingBox=happiness_box, colorSum=548) return happiness
def __init__(self): print 'Starting a new game' self.coordinates = (0, 0) self.location = GameLocation(self.x_offset, self.y_offset, self.width, self.height) self.vision = Vision(self.location) self.controller = Controller(self.x_offset, self.y_offset) self.phone = Phone() self._build_buttons() self._reset_food() self._build_customers() self._build_recipes() self.mat = GameObject('Mat', (199, 380))
def create_objects(self): path = "json/objects.json" f = open(path) list_ = json.load(f) for dict_ in list_: class_name = dict_["class_name"] if class_name == "GameObject": o = GameObject(dict_) elif class_name == "Door": o = Door(dict_) elif class_name == "Chest": o = Chest(dict_) elif class_name == "MrsHuff": o = MrsHuff(dict_) self.objects.append(o)
def create_gui_wall(self, position_x, position_y, sprite_name): """Creates the gui wall object.""" cur_sprites = {} sprite_1 = SpriteImage(0, self.pygame_sprites[sprite_name]) cur_sprites[sprite_name] = sprite_1 cur_object = GameObject(self.cur_game_obj_id, 1, position_x, position_y, None, cur_sprites) cur_object.cur_sprite_image = sprite_1 self.game_objects[self.cur_game_obj_id] = cur_object self.cur_game_obj_id += 1 return cur_object
def init_object(o, name): if not 'x' in o: o['x'] = 0 if not 'y' in o: o['y'] = 0 if not 'char' in o: o['char'] = '@' if not 'color' in o: o['color'] = 'black' if not 'type' in o: return GameObject(o['x'], o['y'], o['char'], o['color'], name) elif o.get('type') == 'npc': if 'dialog' in o: dialog = o['dialog'] else: dialog = 'default' return NPC(o['x'], o['y'], o['char'], o['color'], name, dialog)
def prototype_to_game_object(prototype): id = prototype.get('id') race = prototype.get('race') char = prototype.get('char') color = prototype.get('color') level = prototype.get('level') g_class = prototype.get('class') min_health = prototype.get('min_health') max_health = prototype.get('max_health') inventory = prototype.get('handaxe') blocks = prototype.get('true') return GameObject(id=id, race=race, char=char, color=color, level=level, hp=max_health, inventory=inventory, blocks=blocks)
def spawn_enemy(self, index): definition = enemy.enemies_definitions[index] enemy_object = GameObject( map.get_tile_coords( map_settings.settings.enemies_path_coords[0][0] - 1, map_settings.settings.enemies_path_coords[0][1]), (1, 1), 0) # for f in file_utils.get_all_files_in_path(ENEMIES_PATH + definition.sprites_directory): # print(f) enemy_object.add_component(DynamicSprite).init_component( pos=(0, -map.TILE_SIZE / 4), size=(map.TILE_SIZE, map.TILE_SIZE), angle=0, images_paths=file_utils.get_all_files_in_path( ENEMIES_PATH + definition.sprites_directory), alpha=True) enemy_object.add_component(DynamicSprite).init_component( pos=(0, -map.TILE_SIZE / 4), size=(map.TILE_SIZE, map.TILE_SIZE), angle=0, images_paths=file_utils.get_all_files_in_path( ENEMIES_PATH + definition.sprites_directory + "/reversed"), alpha=True) enemy_object.get_components(DynamicSprite)[1].change_activity(False) enemy_object.add_component(StaticSprite).init_component( pos=(250, -20), size=(map.TILE_SIZE, map.TILE_SIZE), angle=0, image_path=ENEMIES_PATH + "hp_bar.png", z_pos=800, alpha=True) enemy_object.add_component(Enemy).init_component( path_coords=map_settings.settings.enemies_path_coords, definition=definition, game_mode=self.game_mode) session_data.enemies_left -= 1
def __init__(self): self.game_map = Map(MAP_WIDTH, MAP_HEIGHT) self.objects = [] start_room = self.game_map.rooms[0] playerx = start_room.w / 2 + start_room.x1 playery = start_room.h / 2 + start_room.y1 self.spawn_game_object(playerx, playery, id="player", name="Gromash the Corpse-Eater", char='@', color=libtcod.white, blocks=True, hp=100, inventory=['handaxe']) npc = GameObject(playerx, playery + 2, name="commoner", char='c', color=libtcod.yellow, blocks=True, hp=10) self.load_assets() self.commands = deque() self.commands_history = [] self.game_time = datetime.now() self.scheduler = TimeSchedule() self.turns = 0 self.turnsTaken = {}
def create_test_obj(self, position_x, position_y, obj_type): """Creates the test object.""" debug_sprites = {} sprite_name = "" if obj_type == 0: sprite_name = "debug_1.png" else: sprite_name = "debug_2.png" sprite_debug_1 = SpriteImage(0, self.pygame_sprites[sprite_name]) debug_sprites[sprite_name] = sprite_debug_1 debug_1_object = GameObject(self.cur_game_obj_id, 0, position_x, position_y, None, debug_sprites) debug_1_object.cur_sprite_image = sprite_debug_1 self.game_objects[self.cur_game_obj_id] = debug_1_object self.cur_game_obj_id += 1 return cur_object
self.target = target def update(self, screen): #Ändra hastigheten, så att vi följer spelaren x_dist = self.target.x - self.x y_dist = self.target.y - self.y distance = math.hypot(x_dist, y_dist) self.hastighet_x = self.speed * x_dist / distance self.hastighet_y = self.speed * y_dist / distance GameObject.update(self, screen) character = GameObject(x=window_width / 2, y=window_height / 2, image=character_image) enemy = Enemy(x=window_width / 4, y=window_height / 4, target=character) platforms = [ Platform(25, window_height - 70), Platform(window_width / 2, 170), Platform(window_width - 100, window_height - 70), ] #Define some variables for our game exit = False up_pressed = False down_pressed = False left_pressed = False
"""Run game.""" import pygame from game import Game from game_object import GameObject from player import Player pygame.init() size = width, height = 320, 240 screen = pygame.display.set_mode(size) game = Game(screen) player = Player('assets/circle.png') ball = GameObject('assets/circle.png') game.spawn(ball, (50, 50)) game.spawn(player, (width / 2, height / 2)) clock = pygame.time.Clock() while True: clock.tick(60) game.draw()
def __init_borders__(self, width, height): borders = [GameObject('BORDER', QPoint(-1, -1), width, 1, 1), GameObject('BORDER', QPoint(-1, -1), 1, height, 1), GameObject('BORDER', QPoint(0, height), width, 1, 1), GameObject('BORDER', QPoint(width, 0), 1, height, 1)] self.objects += borders
return np.array(export_array) def export_txtr(obj): txtr_array = np.zeros((64, 64)).astype(np.uint32) texture = (obj.texture * 255).astype(np.uint32) texture = np.transpose(texture, (1, 0, 2)) texture = texture[:, ::-1, :] txtr_array = texture[:, :, 2] + texture[:, :, 0] * 256 + texture[:, :, 1] * 256 * 256 return txtr_array.flatten() if __name__ == '__main__': obj = GameObject('0') obj.load_mesh('../data/deer.obj') obj.set_scale(1 / 30) mesh_array = export_mesh(obj) np.save('01_mesh.npy', mesh_array) obj.translate_x(10) obj.rotate_y(-35) np.save('01_trns.npy', obj.transform) obj = GameObject('1') obj.load_mesh('../data/cube.obj') obj.set_scale(100) mesh_array = export_mesh(obj) np.save('02_mesh.npy', mesh_array) obj.translate_x(-50) obj.translate_y(-100)
def __init__(self, parent, screen): # controls how held keys are repeated. The first number is the delay in milliseconds, the second is the interval # at which the keys are repeated pygame.key.set_repeat(1, 1) # Set the parent driver self.parent = parent # sets screen self.screen = screen # creates an empty array called events self.events = [] # sets map width self.map_width = SCREEN_SIZE[0] * MAP_WIDTH // TILE_SIZE # sets map height self.map_height = SCREEN_SIZE[1] * MAP_HEIGHT // TILE_SIZE # sets screen width self.screen_width = SCREEN_SIZE[0] // TILE_SIZE # sets screen height self.screen_height = SCREEN_SIZE[1] // TILE_SIZE # sets background sprite path background = pygame.image.load("resources/graphics/forest.png") # scales background using the path defined above as the background self.background = pygame.transform.scale(background, SCREEN_SIZE) # where camera is on the screen, x position self.x_offset = (MAP_WIDTH - 1) * self.screen_width // 2 # where camera is on the screen, y position self.y_offset = (MAP_HEIGHT - 1) * self.screen_height // 2 # creates an empty array called objects self.objects = [] # variable that determines player location and xml self.player = Player(self.map_width // 2, self.map_height // 2, load_xml("resources/xml/player.xml"), self) # appends the player to objects self.objects.append(self.player) # load the rock xml rock_xml = load_xml("resources/xml/rock.xml") # rock sprite directory is set up rock = pygame.image.load("resources/graphics/rock.png") # width of the rock w = int(rock_xml.get('width')) # height of the rock h = int(rock_xml.get('height')) # path to zombie image self.zombie_img = pygame.image.load( "resources/graphics/enemies/zombie.png") # makes rocks appear at a certain boundary on the top and bottom (x axis) for x in range(self.screen_width, self.screen_width * (MAP_WIDTH - 1), w): self.objects.append( GameObject(x, self.screen_height, w, h, self, image=rock, active=True)) self.objects.append( GameObject(x, self.screen_height * (MAP_HEIGHT - 1), w, h, self, image=rock, active=True)) # makes rocks appear at a certain boundary on the left and right (y axis) for y in range(self.screen_height, self.screen_height * (MAP_HEIGHT - 1), h): self.objects.append( GameObject(self.screen_width, y, w, h, self, image=rock, active=True)) self.objects.append( GameObject(self.screen_width * (MAP_WIDTH - 1), y, w, h, self, image=rock, active=True)) # Preload the xml so we can reuse it self.zombie_xml = load_xml("resources/xml/zombie.xml") # Set a score value, initially 0 self.score = 0 self.scoreText = font_small.render(str(self.score), True, RED_TEXT_COLOUR, self.screen)