示例#1
0
文件: paths.py 项目: danidee10/Maven
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.calculateButton.clicked.connect(self.find_paths)
        self.ui.clearButton.clicked.connect(self.ui.tableWidget.clearContents)
        self.ui.addRowButton.clicked.connect(self.add_row)
        self.ui.delRowButton.clicked.connect(self.del_row)
        self.ui.viewResourceButton.clicked.connect(self.start_resource_loading)
        self.actionHelp = QtGui.QAction('Help',
                                        self,
                                        statusTip="Help and Docs",
                                        triggered=self.help)
        self.actionHelp.setObjectName("actionHelp")
        self.ui.menubar.addAction(self.actionHelp)
        self.actionAbout = QtGui.QAction('About',
                                         self,
                                         statusTip="About Maven",
                                         triggered=self.about)
        self.actionAbout.setObjectName("actionAbout")
        self.ui.menubar.addAction(self.actionAbout)

        self.all_activities = None  # created because self.start_resource_levelling can't access all the activities
        self.result = None
        self.success = 'No'
        self.progress = 'Yes'
        self.resource_level = Level()
示例#2
0
 def test_delete_character_in_all_sets_and_scoring(self):
     level = Level('level1.txt')
     walls = copy.deepcopy(level.Wall)
     monsters = copy.deepcopy(level.Monster)
     previous_monsters_positions = [
         monster.position for monster in monsters
     ]
     previous_walls_positions = [
         wall.position for wall in walls if wall.is_destroyed
     ]
     list_of_characters = [level.BomberMan, level.Monster, level.Wall]
     explode_area = {Point(6, 1), Point(5, 1), Point(4, 1), Point(5, 2)}
     for point in explode_area:
         level.delete_character_in_all_sets_and_scoring(
             list_of_characters, point)
     monsters_positions = [monster.position for monster in level.Monster]
     walls_positions = [
         wall.position for wall in level.Wall if wall.is_destroyed
     ]
     destroyed_walls = set()
     for w in previous_walls_positions:
         if w not in walls_positions:
             destroyed_walls.add(w)
     killed_monsters = set()
     for m in previous_monsters_positions:
         if m not in monsters_positions:
             killed_monsters.add(m)
     self.assertEqual(set([Point(6, 1), Point(5, 2)]), destroyed_walls)
     self.assertEqual(set([Point(5, 1)]), killed_monsters)
示例#3
0
    def setup(self):
        scr_size = self.app.screen.get_size()

        self.level = Level(scr_size)
        self.level.restart()

        self.cheat_idx = 0

        self.background = TiledImage(load_image("grass"))

        # makes things look a bit nicer for some reason
        w = self.background.rect.width
        self.background.rect.move_ip(-w / 2, -w / 2)

        self.l_shadow = ShadowLayer(scr_size)
        self.l_sprite = Layer(scr_size)

        self.sprites = Group()

        self.app.scores.reset()

        self.font = pygame.font.Font(None, 60)

        self.cheating = False

        play_song("maintheme", volume=0.7)
 def __init__(self, player):
     '''call parent constructor'''
     Level.__init__(self, player)
     self.level_limit = -10000
     '''array with with width, height, x, and y of platform'''
     level = [
         [210, 70, 500, 500],
         [210, 70, 800, 400],
         [210, 70, 1120, 280],
         [210, 70, 2000, 300],
         [210, 70, 1800, 500],
         [210, 70, 2900, 400],
     ]
     walls = [[70, 600, 0, 0], [70, 600, 3200, 0]]
     '''go through the array and add platforms'''
     for platform in level:
         block = Platform(platform[0], platform[1])
         block.rect.x = platform[2]
         block.rect.y = platform[3]
         block.player = self.player
         self.platform_list.add(block)
     '''do the same for level walls'''
     for wall in walls:
         block = Wall(wall[0], wall[1])
         block.rect.x = wall[2]
         block.rect.y = wall[3]
         block.player = self.player
         self.walls_list.add(block)
     '''add enemies to level'''
     self.enemy_list.add(Enemy())
     self.enemy_list.add(Enemy())
示例#5
0
 def start(self):
     self.tk.geometry(
         str(self.config['width'] * self.size_x) + 'x' +
         str(self.config['height'] * self.size_y))
     self.level = Level(self)
     self.level.render(1)
     self.tk.mainloop()
示例#6
0
    def __init__(self, player, height=70, screen=None, level_design=None):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self,
                       player,
                       height=height,
                       screen=screen,
                       level_design=level_design)

        # Create platforms with sprites
        level = self.get_level_from_design(using_sprite=True,
                                           sprite_left=GRASS_LEFT,
                                           sprite_right=GRASS_RIGHT,
                                           sprite_center=GRASS_MIDDLE,
                                           pos_y=screen.get_rect().height -
                                           PLAYER_HEIGHT)

        # This is the door level change.
        # =======================================
        door = Door(70, 70, self.level_limit_x, self.level_limit_y, DOOR)
        self.background_sprites.add(door)
        # =======================================

        for platform in level:
            block = Platform(image=platform[4])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)
示例#7
0
 def import_level_clicked(self):
     filename = filedialog.askopenfilename(defaultextension=".mcl",
                                           filetypes=[("M.C. Kids Level",
                                                       "*.mcl"),
                                                      ("All Files", "*")])
     if len(filename):
         with open(filename, "rb") as fp:
             data = fp.read()
             if data[0:4] == bytearray('MCLV', encoding='utf8'):
                 # New type
                 if data[4] != 0x01:
                     messagebox.showerror(
                         "Error", "The version used to save this level, "
                         "is higher than this version of the editor understands."
                     )
                     return
                 level = Level.load_level(self.current_stage, data[12:],
                                          self.rom_file)
                 level.start_x = data[5]
                 level.start_y = data[6]
                 level.flags1 = data[7]
                 level.flags2 = data[8]
                 level.stage_sprite_index = data[9]
                 level.bg_color = data[10]
                 level.music = data[11]
                 self.rom_file.levels[self.current_stage] = level
                 # Reload palettes to make colors correct
                 self.draw_stage()
             else:
                 self.rom_file.levels[
                     self.current_stage] = Level.load_level(
                         self.current_stage, data, self.rom_file)
                 self.draw_stage()
示例#8
0
    def __init__(self):
        Level.__init__(self)
        self.name = "Breakout Minus Bricks 2"

        # Rect that objects are allowed to move inside
        global move_space
        move_space = pygame.Rect(grid_step, grid_step, shared.dim.x - 2*grid_step, shared.dim.y - 2*grid_step)
    def gameWin(self):
        self.player.can_move = False
        i = LEVELS.index(self.level.name)
        i += 1
        # Player finished all levels
        if len(LEVELS) == i:
            self.player.heart_sound.stop()
            self.parent.fsm.request('GameWin')
        # Player not yet finished all levels, move to next level
        else:
            self.player.heart_sound.stop()

            # Clean up
            for z in self.zombies[:]:
                z.destroy()
                self.zombies.remove(z)
            for l in self.level.light_nodes:
                render.setLightOff(l)
            self.level.destroy()
            self.level = None

            # Reinit
            self.level = Level(self, LEVELS[i])
            self.collision_manager.createLevelCollision(self.level)
            self.spawnEnemy()
            self.player.node.setPos(self.level.start_pos[0] * TILE_SIZE,
                                    self.level.start_pos[1] * TILE_SIZE,
                                    TILE_SIZE * ASPECT / 1.5)
            self.player.can_move = True
            self.player.bullets += 2
            if self.player.bullets > self.player.max_bullets:
                self.player.bullets = self.player.max_bullets
            self.parent.gameui.refreshBullets()
            render.setShaderAuto()
    def init_level(self, level):
        self.current_level = Level(level)
        #self.draw_level(self.current_level.get_matrix())

        #  mark game as not finished
        self.game_finished = False
        self.player_alive = True

        #  number of time steps elapsed in a level
        self.elapsed_time_step = 0

        #  initialize number of apples player collected so far in curret level
        self.collected_apple_count = 0

        #  create player object
        player_pos = self.current_level.get_player_pos()
        player_current_row = player_pos[0]
        player_current_col = player_pos[1]
        self.player = Player(player_current_row, player_current_col)

        #  create apples
        self.apples = []
        apple_positions = self.current_level.get_apple_positions()
        for pos in apple_positions:
            r = pos[0]
            c = pos[1]
            self.apples.append(Apple(r, c))

        #  count number of apples
        self.total_apple_count = len(self.apples)
示例#11
0
 def enter(self, level_file):
     """Called every time the game is switched to this state."""
     if level_file:
         if not self.world or self.world.lvlFile != level_file:
             self.world = Level(self.gc.SCREEN_SIZE, level_file)
     else:
         assert(self.world)
示例#12
0
    def __init__(self, option_handler):
        self.option_handler = option_handler
        self.state = State.MENU

        self.level = Level()
        self.players = dict()
        self.colliders = []

        self.time_scale = 1.0

        self.camera = Camera([0, 0], self.option_handler.resolution)

        self.respawn_time = 50.0

        self.menu = MainMenu()
        self.player_menus = [
            PlayerMenu((6 * i - 9) * basis(0)) for i in range(4)
        ]
        self.options_menu = OptionsMenu()
        self.options_menu.set_values(self.option_handler)

        self.network = None
        self.network_id = -1
        self.obj_id = -1

        self.controller_id = 0
示例#13
0
    def loadcontent(self):
        Level.loadcontent(self)
        obj = Asset(self.imageSprites, 160, 321, 43, 63, 345, 0)
        self.objects.append(obj)

        obj = Asset(self.imageSprites, 100, 257, 86, 128, 259, 0)
        self.objects.append(obj)
示例#14
0
文件: main.py 项目: joaompinto/Zunga
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()
示例#15
0
def run_game():
	
	state = StartState() 
	level = Level()	

	while 1:
		for event in pygame.event.get():
			if event.type == STATECHANGE:
				if event.event_id == 'won':
					next_room = level.next_room()
					
					if next_room == 'Win':
						state = Win()
					else:
						state = Room(state.whale, enemies=level.enemies[next_room])

				elif event.event_id == 'lose':
					state = Lose()	
				
				elif event.event_id == 'start_over':
					level = Level()
					state = StartState()
			else:
				state.handle_event(event)
		state.update()
		pygame.time.delay(10)
示例#16
0
    def __init__(self, server_port, full_screen=False):
        pygame.init()
        infoObject = pygame.display.Info()
        pygame.display.set_caption("Tank War")
        pygame.key.set_repeat(10)

        self.level = Level()
        self.mode = 'Single Player'
        self.players = []
        self.available_servers = []
        self.timer = pygame.time.Clock()
        self.font = pygame.font.Font('freesansbold.ttf', 36)
        self.small_font = pygame.font.Font('freesansbold.ttf', 24)
        self.tiny_font = pygame.font.Font('freesansbold.ttf', 18)
        self.active_menu = 'Main menu'

        self.network = Network(server_port, self)
        self.start_game = False

        self.enemies = pygame.sprite.Group()
        self.no_enemies = 2

        if full_screen == True:
            self.screen = pygame.display.set_mode(
                (infoObject.current_w, infoObject.current_h))
        else:
            self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
示例#17
0
    def generate_level(self):
        self._level_count += 1
        min_rooms = 5
        size = 20, 20

        # generate the tile types
        tiletypes, rooms = self._level_generator.generate(size, min_rooms)
        level = Level(self.player, tiletypes, self._level_count)

        # generate the objects
        objects = self._object_generator.generate(min_rooms, self._level_count)
        self._object_generator.place_objects(objects, level)

        # generate monsters
        species = self._species_generator.generate_level(self._level_count)
        beings = [Being(self.controller, s) for s in species]
        self._species_generator.place_beings(beings, level)

        # set the player on a up staircase
        tile = level.staircases_up[0]
        level.add_being(tile, self.player)

        self.levels.append(level)
        self._current_level = level

        # housekeeping
        # FIXME this will need to move to change_level
        for being in [b for b in level.beings]:
            being.new_level(level._size)
        self.turn_done(move_monsters=False)

        for being in [t.being for t in level.values() if t.being and self.player.vision.can_see(t)]:
            being.has_been_seen = True

        return level
示例#18
0
class Game():
    def __init__(self, config):
        self.empty = 'empty'
        self.brick = 'brick'
        self.rang = 'rang'
        self.concrete = 'concrete'
        self.fire_item = 'fire'
        self.config = config
        self.width = config['width']
        self.height = config['height']
        self.size_x = self.config['size_x']
        self.size_y = self.config['size_y']
        self.tk = Tk()
        self.coordinates = [[self.empty] * config['height']
                            for i in range(config['width'])]

        self.canvas = Canvas()
        self.create_rectangle(0,
                              0,
                              self.config['width'],
                              self.config['height'],
                              fill=config['bg'])
        self.canvas.pack(fill=BOTH, expand=1)
        self.wall = Wall(self)
        self.ladder = Ladder(self)
        self.fire = Fire(self)
        self.human = Human(self)

    def start(self):
        self.tk.geometry(
            str(self.config['width'] * self.size_x) + 'x' +
            str(self.config['height'] * self.size_y))
        self.level = Level(self)
        self.level.render(1)
        self.tk.mainloop()

    def create_line(self, x1, y1, x2, y2, **kwargs):
        self.canvas.create_line(x1 * self.size_x, y1 * self.size_y,
                                x2 * self.size_x, y2 * self.size_y, kwargs)

    def create_rectangle(self, x1, y1, x2, y2, **kwargs):
        self.canvas.create_rectangle(x1 * self.size_x, y1 * self.size_y,
                                     x2 * self.size_x, y2 * self.size_y,
                                     kwargs)

    def create_oval(self, x1, y1, x2, y2, **kwargs):
        self.canvas.create_oval(x1 * self.size_x, y1 * self.size_y,
                                x2 * self.size_x, y2 * self.size_y, kwargs)

    def create_polygon(self, points, **kwargs):
        points_by_size = []
        j = 0
        for i in points:
            points_by_size.append(i *
                                  (self.size_x if j % 2 == 0 else self.size_y))
            j += 1
        self.canvas.create_polygon(points_by_size, kwargs)

    def create_image(self, x, y, **kwargs):
        self.canvas.create_image(x * self.size_x, y * self.size_y, kwargs)
示例#19
0
 def generate_next_level(self):
     if self.current_level < (self.config['game']['levels'] - 1):
         return Level(self.config['level']).generate().with_stairs_up(
             self.hero).with_stairs_down()
     else:
         return Level(self.config['level']).generate().with_stairs_up(
             self.hero)
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    settings = Settings()
    clock = pygame.time.Clock()
    clock.tick(60)

    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))

    pygame.display.set_caption("Oh My Blocks")

    # Make the Play button.
    play_button = Button(settings, screen, "Play")

    # Make a ship, a group of bullets and blocks.
    ship = Ship(settings, screen)
    bullets = Group()
    blocks = Group()

    level = Level(settings, screen, blocks)
    level.getLevel()

    while True:

        game.check_events(settings, screen, ship, bullets)
        game.update_bullets(settings, screen, ship, blocks, bullets)
        game.update_screen(settings, screen, play_button, blocks, ship,
                           bullets)
示例#21
0
def generate_shop(w, h, shop_items):
	level = Level(w, h, is_shop=True)

	for x,y in range2d(w, h):
		t = level.tiles[x][y]
		if x == 0 or y == 0 or x == w-1 or y == h-1:
			t.img = spr.WOOD_WALL
			t.blocking = True
			t.transparent = False
		else:
			t.img = spr.WOOD_FLOOR
			t.blocking = False
			t.transparent = True

	for a,b in box2d(2, 2, 5, 5):
		level.add_item((a,b), random.choice(shop_items))
	for a,b in box2d(9, 2, 5, 5):
		level.add_item((a,b), random.choice(shop_items))
	for a,b in box2d(2, 9, 5, 5):
		level.add_item((a,b), random.choice(shop_items))
	for a,b in box2d(9, 9, 5, 5):
		level.add_item((a,b), random.choice(shop_items))

	level.illuminated = True
	return level
示例#22
0
    def __init__(self):
        super().__init__()

        # initialize various windows used in this scene:
        # gamewin -> main map view
        # hudwin -> left stripe wtih key char information
        # msgwin -> basic messages window
        self.gamewin = win.Window(10, 0, win.screenwidth - 10,
                                  win.screenheight)
        self.hudwin = win.Window(0, 0, 10, win.screenheight)
        self.hudwin.setbg(win.color(50, 50, 50))
        self.msgwin = win.Window(self.hudwin.width, win.screenheight - 10,
                                 win.screenwidth - self.hudwin.width, 10)
        self.msgwin.setalpha(1.0, 0.0)

        # create player and level object
        self.player = gameobject.create('player', 50, 50)
        self.level = Level(self.player, 200, 200, self.gamewin)

        # create initial dungeon and compute the initial player field of view and player position.
        dungeon.createdungeon(self.level, 2)
        self.level.computefov()

        self.id = "Game Scene"

        self.keydict = {
            ',': (self._handlestairs, 'upstair'),
            '.': (self._handlestairs, 'downstair'),
        }
示例#23
0
 def start(self, mario):
     Level.start(self, mario)
     musicfilepath = "game\\assets\\musics\\hautedhouse.mp3".format(
         self.name)
     if os.path.exists(musicfilepath):
         pygame.mixer.music.load(musicfilepath)
         pygame.mixer.music.play()
示例#24
0
    def __init__(self, player, height=70, screen=None, level_design=None):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self,
                       player,
                       height=height,
                       screen=screen,
                       level_design=level_design)

        # Create platforms with sprites
        level = self.get_level_from_design(using_sprite=True,
                                           sprite_left=STONE_PLATFORM_LEFT,
                                           sprite_right=STONE_PLATFORM_RIGHT,
                                           sprite_center=STONE_PLATFORM_MIDDLE,
                                           pos_y=screen.get_rect().height -
                                           PLAYER_HEIGHT)

        # Add door to finish level
        door = Door(70, 70, self.level_limit_x, self.level_limit_y, DOOR)
        self.background_sprites.add(door)

        # Add door to enter level
        door2 = Door(70, 70, (screen.get_rect().width // 2) - 50,
                     screen.get_rect().height - PLAYER_HEIGHT, DOOR)
        self.background_sprites.add(door2)

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(image=platform[4])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            block.player = self.player
            self.platform_list.add(block)
示例#25
0
    def __init__(self):

        # general setup
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGTH))
        pygame.display.set_caption('Arena')
        self.clock = pygame.time.Clock()

        self.windowSurface = pygame.display.set_mode((WIDTH, HEIGTH))
        self.windowSurface.fill((255, 153, 0))

        self.imag_bg = pygame.image.load('../graphics/menumain.png')
        self.windowSurface.blit(self.imag_bg, (50, 0))
        pygame.display.update()

        self.imag_game_over = pygame.image.load('../graphics/gameover.png')
        self.imag_player_win = pygame.image.load('../graphics/playerwin.png')

        self.level = Level()
        self.font = pygame.font.SysFont(None, 48)

        self.resultado = -1

        # sound
        main_sound = pygame.mixer.Sound('../audio/music.mp3')
        main_sound.set_volume(0.3)
        main_sound.play(loops=-1)
示例#26
0
 def __init__(self):
     self.guess = 2
     self.end = False
     self.time = 0
     player = (0, 11 * 50, 36)
     base = (10 * 50, 14 * 50)
     self.levels = [Screen(self, screen, (),
                           (365, 459, 330, 111, (255, 255, 255), 'Начать игру'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Level(self, screen, wallist, brwalls, snowlist, snowmanlist, player, base),
                    Screen(self, screen, (("Первый уровень пройден", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'Продолжить'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Level(self, screen, wallist2, brwalls2, snowlist2, snowmanlist2, player, base),
                    Screen(self, screen, (("Второй уровень пройден", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'Продолжить'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Level(self, screen, wallist3, brwalls3, snowlist3, snowmanlist3, player, base),
                    Screen(self, screen, (("Третий уровень пройден", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'Продолжить'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Level(self, screen, wallist4, brwalls4, snowlist4, snowmanlist4, player, base),
                    Screen(self, screen, (("Четвёртый уровень пройден", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'Продолжить'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Level(self, screen, [], [], snowlist5, [], player, (1000, 1000)),
                    Screen(self, screen, (("Игра окончена! Вы победили", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'В главное меню'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход')),
                    Screen(self, screen, (("Вы проиграли. Удачи в следующий раз", 400, 300, (250, 250, 0)),),
                           (365, 459, 330, 111, (255, 255, 255), 'В главное меню'),
                           (724, 459, 330, 111, (255, 255, 255), 'Выход'))]
示例#27
0
 def enter(self):
     self._g_root = greenlet.getcurrent()
     self._g_loop = greenlet.greenlet(self._loop)
     self.message_log = MessageLog()
     self.level = Level(self, self.DUNGEON_SIZE_X, self.DUNGEON_SIZE_Y)
     self.game.window.push_handlers(self)
     self._g_loop.switch()
示例#28
0
class GameContext:
	def __init__(self, engine):
		self.engine = engine
		self.font = engine.game_data[FONT]
		self.current_level = 0
		self.current_level_id = self.engine.game_data[LEVELS][self.current_level]
		self.level = Level(load(self.engine.game_data[LEVEL_DATA][self.current_level_id][FILE]), engine)
		controls = engine.game_data[CONTROLS]
		self.down_control_map = {
			controls[LEFT]: self.level.player.left_down,
			controls[RIGHT]: self.level.player.right_down,
			controls[JUMP]: self.level.player.jump_start,
		}
		self.up_control_map = {
			controls[LEFT]: self.level.player.left_up,
			controls[RIGHT]: self.level.player.right_up,
			controls[JUMP]: self.level.player.jump_end,
		}
		print "Game Created"
	def handle_mouse_up_event(self, event):
		pass
	def handle_key_down_event(self, event):
		if self.down_control_map.has_key(event.key):
			self.down_control_map[event.key]()
	def handle_key_up_event(self, event):
		if event.key == K_ESCAPE:
			self.engine.context = MenuContext(self.engine)
		elif self.down_control_map.has_key(event.key):
			self.up_control_map[event.key]()
	def update(self, delta):
		self.level.update(delta)
	def display(self):
		self.level.draw(self.engine.screen)
示例#29
0
    def __init__(self):
        # init mixer first to prevent audio delay
        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.mixer.init()

        pygame.init()
        pygame.display.set_caption('NEXTGAME')

        self.option_handler = optionhandler.OptionHandler()

        mode = 0
        if self.option_handler.fullscreen:
            mode = pygame.FULLSCREEN

        self.screen = pygame.display.set_mode(self.option_handler.resolution,
                                              mode)

        self.image_handler = imagehandler.ImageHandler()
        self.input_handler = inputhandler.InputHandler()

        self.clock = pygame.time.Clock()
        self.time_step = 15.0 / self.option_handler.fps
        self.font = pygame.font.Font(None, 30)

        self.level = Level()

        self.grid_color = [150, 150, 150]

        self.wall_start = None
        self.grabbed_object = None
        self.grab_offset = np.zeros(2)
        self.object_types = ['wall', 'platform']
        self.type_index = 0

        self.camera = Camera([0, 0], self.option_handler.resolution)
示例#30
0
class Genotype:
    
    #Add the map as a genotype and phenotype
    def __init__(self):
        self.chromosomes = np.zeros(0, dtype=int)

    def randomize(self, chromosomeSize, trajectory):
        self.level = Level(trajectory.level_width,trajectory.level_height)
        self.level.generate_from_trajectory(trajectory, random.uniform(0,1))
        self.phenotype = Phenotype(self.level)
        self.chromosomes = self.level.cells.flatten()
        self.trajectory = trajectory
#        np.set_printoptions(threshold=np.nan)
#        print(self.chromosomes)
#        print("another genotype")
        
        """
        for i in range(chromosomeSize):
            self.chromosomes.append(random.randint(0,1))
        """
            
    def getPhenotype(self):
        self.phenotype.levelFromChromosomes(self.chromosomes, self.trajectory,
                                            self.trajectory.level_width, self.trajectory.level_height)
        return self.phenotype
示例#31
0
class Game(object):
    def __init__(self, _sm):
        """Inicializa todos los componentes del estado.
			Parámetros:
				_sm -- Gestor de estados por si se quiere moverse entre estados."""
        self.__level = Level()
        self.__player = Player()
        self.__kong = Kong()
        self.__peach = Peach()

    def render(self, _screen):
        """Dibuja todos los compones del juego.
			Parámetros:
				_screen -- Superficie donde se dibujarán los componentes."""
        self.__level.render(_screen)
        self.__player.render(_screen)
        self.__kong.render(_screen)
        self.__peach.render(_screen)

    def update(self, _dt):
        """Actualiza todos los componentes.
			Parámetros:
				_dt -- Tiempo que ha transcurrido en milisegundos que ha
					transcurrido desde la última vez que se ejecutó este método."""
        self.__player.update(_dt, self.__level)
        self.__kong.update(_dt, self.__level, self.__player)
        self.__peach.update(_dt)
示例#32
0
 def load(self):
     fn = filedialog.askopenfilename(**self.file_opt)
     if fn:
         self.level = Level(fn)
     self.title.set(self.level.title)
     self.text.delete(1.0, END)
     self.text.insert(1.0, self.level.text)
     self.redraw()
示例#33
0
    def __init__(self):

        pygame.init()
        self.screen = pygame.display.set_mode((Width, Height))
        pygame.display.set_caption('Scary Puzzle :)')
        self.clock = pygame.time.Clock()

        self.level = Level()
示例#34
0
    def setup_level(self, level_number):
        """Setup the game level."""

        self.level = Level(self, level_number)
        self.level.build()

        if not self.debug:
            utility.save_object(self, 'level_start')
示例#35
0
    def __init__(self, _sm):
        """Inicializa todos los componentes del estado.
			Parámetros:
				_sm -- Gestor de estados por si se quiere moverse entre estados."""
        self.__level = Level()
        self.__player = Player()
        self.__kong = Kong()
        self.__peach = Peach()
示例#36
0
文件: world.py 项目: txcism/pygame
 def make_level(self, x, y):
     level = Level(x, y, self)
     #count level from 0 NOT 1
     level.number = len(self.level_list)
     #group for render & collide
     self.platfrom_group.add(level.platform)
     print('level maked!!!')
     return level
示例#37
0
    def __init__(self, debug=False, level=1):

        self.debug = debug
        self.control = Control(self)
        self.level = Level(self)
        self.player = Player(self)
        self.ui = StartUI(self)
        self.setup(level_number=level)
示例#38
0
	def __init__(self, player, AI):
		Level.__init__(self,player, AI)
		
		#enemies = [[40, 40, 0, 0, 'Basic_enemy', 0],
		#		[40, 40, 0, 0, 'Basic_enemy', 1]]

		self.parse_map('tutorial_map.txt');
		
		"""
示例#39
0
class Engine(object):

    def __init__(self, world_size=WORLD_SIZE):
        self.world_center = Point((world_size // 2, world_size // 2))
        self.world_size = world_size
        self.snake = Snake(start=self.world_center, start_length=SNAKE_START_LENGTH, growth_pending = GROWTH_PENDING)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.score = 0
        self.controller = Controller(self.level.level_render)

    def reset(self):
        """Start a new game."""
        self.playing = True
        self.score = 0
        self.snake = Snake(start=self.world_center,
                           start_length=SNAKE_START_LENGTH)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.play()

    def update(self, dt):
        """Update the game by dt seconds."""

        self.check_input()
        # time.sleep(dt)
        if self.snake.update():
            self.level.update_level()
            self.level.level_render.draw_text(
                Point((0, 0)), 'Score {}'.format(self.score))
            self.level.show_level()
            head = self.snake.get_head()
            # If snake hits a food block, then consume the food, add new
            # food and grow the snake.
            if head in self.level.food:
                self.eat(head)
            if self.snake.self_intersecting():
                raise GameOver('snake intersecting')
            if head in self.level.blocks:
                raise GameOver('snake try eat block')
        time.sleep(dt)

    def eat(self, head=None):
        print('mmm, tasty')
        self.level.food.remove(head)
        self.snake.grow()
        self.score += len(self.snake) * SEGMENT_SCORE

    def play(self):
        """Play game until the QUIT event is received."""
        while True:
            try:
                self.update(TIME_DELTA)
            except GameOver, err:
                print(str(err))
                print('You score {}'.format(self.score))
                time.sleep(3)
                self.reset()
示例#40
0
 def __init__(self, level, game, raw, *args, name="GenericLoadScreenLevel",distortion_params=False,color=(30,30,30),scroll=0,autoscroll_speed=(0.0,0.0),vis_ofs=0,audio_section="current",**kwargs):
     Level.__init__(self, level, game, raw, *args,
         distortion_params=distortion_params,
         color=color,
         scroll=scroll,
         autoscroll_speed=autoscroll_speed,
         vis_ofs=vis_ofs,
         audio_section=audio_section,
         **kwargs
     )
示例#41
0
def solve_monkey(dist = False):
    path = 'screenshots/%s.png' % datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    print('Taking screenshot')
    call(['monkeyrunner', 'monkeyscreen.py', path])
    print('Rotating')
    call(['convert', '-rotate',  '90', path, path])
    
    print('Starting image solver')
    val, xmarks, ymarks = solve_image(path, dist)
    
    print('Generating solution path')
    pathparts = splitext(path)
    pathsol = '%s.sol_path.txt' % pathparts[0]
    solfile = open(pathsol, 'w')
    
    level = Level()
    level.rows = len(val)
    level.cols = len(val[0]) 
    for x, y in product(range(level.cols), range(level.rows)):
        c, t = val[y][x][0]
        if t != 0:
            continue
        #print('Tracing color', c)
        # Found a dot, start
        cx, cy, ct = x, y, 0
        while True:
            # Print current
            #print(cx, cy, ct)
            solfile.write('%d %d\n' % (avg([xmarks[cx], xmarks[cx+1]]), avg([ymarks[cy], ymarks[cy+1]])))
            # Find next
            cx2, cy2, ct2 = -1, -1, -1
            for nx, ny in level.neighbors(cx, cy):
                nc, nt = val[ny][nx][0]
                if nc >= 0 and connects(cx, cy, ct, nx, ny, nt):
                    cx2 = nx
                    cy2 = ny
                    ct2 = nt
                    break
            # Found nothing - done
            if cx2 == -1:
                break
            # Delete current and replace with next
            val[cy][cx][0] = -1, -1
            cx = cx2
            cy = cy2
            ct = ct2
        # Delete last
        val[cy][cx][0] = -1, -1
        solfile.write('0 0\n')
    solfile.close()
    
    print('Solving on device')
    call(['monkeyrunner', 'monkeypath.py', pathsol])
    
    print('DONE')
示例#42
0
def run_game():
  
  pygame.init()
  clock = pygame.time.Clock()
  screen = pygame.display.set_mode((globals['SCREEN_WIDTH'], globals['SCREEN_HEIGHT']), 0, 32)
  
  currently_held_keys = []
  
  #debug stuff
  lvl = Level("testlevel.txt", screen) 
  playerCam = Camera((85,85), globals['SCREEN_WIDTH'], globals['SCREEN_HEIGHT'])
  originCam = Camera((0,0), globals['SCREEN_WIDTH'], globals['SCREEN_HEIGHT'])
  player = Player("resources/robodude.png", screen, (85,85), playerCam)
  currentCam = player.camera
  entities = []
  
  entities.append(player)
 
  while True:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        exit_game()
      if event.type == pygame.KEYDOWN:
        currently_held_keys.append(event.key)
      if event.type == pygame.KEYUP:
        currently_held_keys.remove(event.key)
    
    currentCam = player.camera
    do_render_light = True

    for keydown in currently_held_keys:
      if keydown in globals['WASD_KEYS']:
        player.movement_handler(keydown)
      #debug stuff
      if keydown == pygame.K_1:
        currentCam = originCam
      if keydown == pygame.K_2:
        do_render_light = False
    
    time_passed = clock.tick(50)
    screen.fill(globals['BG_COLOR'])

    # debug stuff
    pygame.display.set_caption('Lightgame : %d fps' % clock.get_fps())
    corners = currentCam.get_corners()
    lvl.draw_visible_level(corners[0], corners[1])
    player.update(time_passed, lvl, currentCam)
    player.draw(currentCam)
    
    lights_per_entity = [entity.lights for entity in entities]
    all_lights = [light for lights in lights_per_entity for light in lights]
    if do_render_light:
      currentCam.render_light(screen, all_lights)

    pygame.display.flip()
示例#43
0
def generate_dungeon(w, h, difficulty=1):
	level = Level(w, h)

	new_map = [[0 for _ in xrange(h)] for _ in xrange(w)]
	# initialize new_map to noise (0.43% filled)
	for x,y in range2d(w, h):
		if random.random() < 0.43:
			new_map[x][y] = 1

	# apply cellular automation
	for i in xrange(2):
		temp_map = [[0 for _ in xrange(h)] for _ in xrange(w)]
		for x,y in range2d(w, h):
			wall_count = 0
			for i,j in box2d(x-1, y-1, 3, 3):
				if 0 <= i < w and 0 <= j < h:
					wall_count += new_map[i][j]
				else:
					# sides = instawall
					wall_count += 3

			if wall_count >= 5:
				temp_map[x][y] = 1

		new_map = temp_map

	# apply changes to actual map
	for x,y in range2d(w, h):
		tile = level.tiles[x][y]
		if new_map[x][y] == 1:
			tile.img = spr.ROCK
			tile.blocking = True
			tile.transparent = False
		else:
			tile.img = spr.MUD_FLOOR
			tile.blocking = False
			tile.transparent = True

	# spawn treasures and creatures
	mr = level.get_main_region()

	treasures = random.sample(mr, difficulty)
	for loc in treasures:
		level.add_item(loc, Item(spr.GOLD_NUGGET, name="gold nugget", value=50+difficulty*25))

	mobs = random.sample(mr, difficulty)
	for loc in mobs:
		c = Creature(level, *loc, hp=difficulty*10, maxhp=difficulty*10, name="malicious slime", gold=10+difficulty*5)
		c.min_atk = difficulty
		c.max_atk = difficulty*2

		level.creatures.append(c)
		
	return level
示例#44
0
	def load_levels(self, f, offset):
		"""Load all the levels in turn, and return the new offset."""
		self.levels = list()
		
		for i in range(1):#self.levelCount):
			l = Level(self, f, offset)
			self.levels.append(l)
			offset = l.get_offset()
		
		self.currentLevel = 0
		self.load_level(self.currentLevel)
示例#45
0
	def __init__(self, player, AI):
		Level.__init__(self,player, AI)

		enemies = {
			'G': initGhost,
			'S': initSpider,
			'M': initMonkey
		}

		self.parse_map('tutorial_map.txt', enemies, initEnemy)
		self.set_background_image('tutorial_background.png')
		self.music = 'levels/forest.mp3'
示例#46
0
class CaterpillarsApp(App):
    def build(self):
        self.progress = self.load_progress()
        self.grid_screen = LevelChooser()
        self.grid_screen.bind(on_level=self.level_choice)
        self.grid_screen.bind(on_wtf=self.wtf)
        self.grid_screen.color_progress(self.progress)
        self.level_screen = Level()
        self.wtf_screen = Help()
        self.level_screen.bind(on_pass=self.success)
        self.root = ScreenManager()
        self.root.add_widget(self.grid_screen)
        self.root.add_widget(self.level_screen)
        self.root.add_widget(self.wtf_screen)
        self.bind(on_start=self.post_build_init)
        return self.root

    def post_build_init(self, ev):
        if ANDROID:
            android.map_key(android.KEYCODE_BACK, 1001)
        win = self._app_window
        win.bind(on_keyboard=self.key_handler)

    def key_handler(self, keyboard, keycode, *args, **kwargs):
        if keycode == (1001 if ANDROID else 32):
            self.root.current = "grid"

    def level_choice(self, instance, level_id, rule):
        self.cur_level = level_id
        self.root.current = "level"
        self.level_screen.start_game(rule)

    #        self.root.current="level"

    def success(self, instance):
        if not self.cur_level in self.progress:
            self.progress.append(self.cur_level)
        self.grid_screen.color_progress(self.progress)
        self.save_progress()
        self.root.current = "grid"

    def wtf(self, *args):
        self.root.current = "wtf"

    def load_progress(self):
        try:
            return map(int, open(os.path.join(CATALOG_ROOT, "progress.txt")).read().split())
        except:
            return []

    def save_progress(self):
        open(os.path.join(CATALOG_ROOT, "progress.txt"), "w").write(" ".join(map(str, self.progress)))
示例#47
0
    def load_level(self, filename):
        surf = pygame.image.load(os.path.join(self.datapath, filename))
        (width, height) = surf.get_size()

        level = [[None for y in range(height)] for x in range(width)]

        for i in range(width):
            for j in range(height):
                pixelcolor = surf.get_at((i,j))
                level[i][j] = self.color_to_tile.get_tile_by_color(pixelcolor)

        lev_obj = Level(level)
        lev_obj.print_level()               
示例#48
0
文件: level1.py 项目: 450W16/MODACT
	def __init__(self, player, AI):
		Level.__init__(self,player, AI)
		
		enemies = {
			'G': initGhost,
			'S': initSpider,
			'M': initMonkey
		}
		
		self.parse_map('level1_map.txt', enemies, initEnemy)
		self.set_background_image('tutorial_background.png')
		self.background_image = pygame.transform.scale(self.background_image, (self.level_width, self.level_height - BLOCK_HEIGHT*3))
		self.music = 'levels/forest.mp3'
示例#49
0
 def _setup(self):
     self._load_resources()
     
     level = Level(self.IMAGE_CACHE)
     level.load("test", "test.txt")
     self.background = level.draw()
     self.screen.blit(self.background, (0, 0))
     
     self.sprites = pygame.sprite.RenderUpdates()
     self.player = Player(image=self.IMAGE_CACHE['sprites'], pos=level.player_spawn(), frame=(0, 1))
     self.sprites.add(self.player)
     
     pygame.display.flip()
示例#50
0
class LevelController:
    """ Controller class for the level """
    
    def __init__(self):
        """ Initialize the Level Controller """
        self.level = Level(4)
        self.minefield_view = MinefieldView(self.level.minefield, self.level.drone)
        
        self.actions = {KAO_UP:self.level.drone.up,
                        KAO_DOWN:self.level.drone.down,
                        KAO_LEFT:self.level.drone.left,
                        KAO_RIGHT:self.level.drone.right,
                        ord('s'):self.level.drone.scan,
                        ord('d'):self.level.drone.defuse,
                        ESCAPE:self.stopRunning}
        
    def run(self):
        """ Run the controller """
        self.running = True
        self.loop()
        
    def loop(self):
        """ Run the controller main loop """
        while self.running:
            print self.minefield_view
            self.processInput()
            self.checkGameOver()
            
    def processInput(self):
        """ Process the input """
        kao_char = getch()
        if kao_char in self.actions:
            self.actions[kao_char]()
            
    def stopRunning(self):
        """ Stop the Controller from running """
        self.running = False
            
    def checkGameOver(self):
        """ Check if the Game is Over """
        if self.level.lost():
            self.stopRunning()
            if self.level.destroyed():
                print "Destroyed!"
            elif self.level.noPower():
                print "No Power!"
            print "Game Over\r"
        elif self.level.won():
            self.stopRunning()
            print "Congratulations! You won!"
示例#51
0
  def add_level(self, feval, sdc, interpolate=None, restrict=None):
    """Add a level to the PFASST hierarchy.

    :param feval: implicit/explicit function evaluator (instance
            of :class:`pfasst.feval.FEval`)
    :param sdc: implicit/explicit SDC sweeper (instance
            of :class:`pfasst.sdc.SDC`)
    :param interpolate: interpolate from coarser level to this
            level (callable)
    :param restrict: restrict from this level to coarser level
            (callable)

    Levels should be added from finest (level 0) to coarest.

    The *interpolate* callable is called as::

    >>> interpolate(yF, yG, fevalF=fevaF, fevalG=fevalG, **kwargs)

    and should interpolate the coarse y values *yG* that
    correspond to the coarse evaluator *fevalG* to the fine y
    values *yF* that correspond to the fine evaluator *fevalF*.
    The (flattened) result should be stored in *yF*.

    The *restrict* callable is called as::

    >>> restrict(yF, yG, fevalF=fevalF, fevalG=fevalG, **kwargs)

    and should restrict the fine y values *yF* that correspond to
    the fine evaluator *fevalF* to the coarse y values *yG* that
    correspond to the coarse evaluator *fevalG*.  The (flattened)
    result should be stored in *yG*.

    """

    level = Level()

    level.feval       = feval
    level.sdc         = sdc
    level.interpolate = interpolate
    level.restrict    = restrict

    level.level       = len(self.levels)
    level.mpi         = self.mpi
    level.state       = self.state
    level.hooks       = {}
    level.sweeps      = 1

    self.levels.append(level)
示例#52
0
 def init (self):
     
     self.level = Level(self.gameConfig.levelFile)
     self.level.init()
     
     self.skyDome = SkyDome()
     self.skyDome.init("textures/sky_1.jpg")
     
     self.camera = Camera()
     
     self.vehicles = []
     for team in self.gameConfig.teams:
         teamVehicles = self.gameConfig.initialPlayers / len(team.bases)
         vehiclesPerBase = self.gameConfig.initialPlayers / len(team.bases)
         for baseId in team.bases:
             base = self.level.bases[baseId]
             base.owner = team
             vehiclesThisBase = int(ceil(vehiclesPerBase))
             teamVehicles -= vehiclesThisBase
             vehiclePositions = self.getInitialVehiclePositions(base, vehiclesThisBase)
             for vehiclePosition in vehiclePositions:
                 # create and place the vehicle
                 vehicle = LightTank(VehicleType)
                 vehicle.init([vehiclePosition[0], vehiclePosition[1], 0], team)
                 self.vehicles.append(vehicle)
                 # the first vehicle is the players
                 if self.selectedVehicle == None:
                     self.selectedVehicle = vehicle
                     
     pathFinder = PathFinder()
     path = pathFinder.findPath(1,1,17,17)
     print path
示例#53
0
文件: stats.py 项目: wader/slippy
  def get(self):
    players = {}
    levels = {}
    fetch = Level.all().fetch(100000)
    for l in fetch:
      levels[l.id] = l
      if not players.has_key(l.udid):
	players[l.udid] = Player()
      players[l.udid].uploaded.append(l)

    ratings = {}
    fetch = LevelStatistics.all().fetch(100000)
    for r in fetch:
      if not players.has_key(r.udid):
	players[r.udid] = Player()
      players[r.udid].ratings.append(r)

    self.w("players: %d<br>" % len(players))
    self.w("<table border=1>")
    for udid, p in players.items():
      self.w("<tr>")
      self.w("<td valign=top>%s</td>" % udid)
      self.w("<td valign=top>")
      for u in p.uploaded:
	self.response.out.write("%s" % u.name)
      self.w("</td>")
      self.w("<td valign=top>")
      for r in p.ratings:
	if levels.has_key(r.levelid):
	  self.response.out.write("%s" % levels[r.levelid].name)
	else:
	  self.response.out.write("<deleted>")
      self.w("</td>")
      self.w("</tr>")
    self.w("</table>")
示例#54
0
文件: title.py 项目: ikn/spaaace
 def __init__ (self, game, event_handler, num_cars = 2):
     event_handler.add_key_handlers([
         (conf.KEYS_BACK, lambda *args: game.quit_backend(), eh.MODE_ONDOWN)
     ])
     Level.__init__(self, game, event_handler, 0, False)
     self.accel = 0
     self.scores = [0] * num_cars
     self._num_players = num_cars
     self.init_opts((
         ('Start', 1, self.start_level),
         ('Players: ', 2, self._num_players, 1, 4, 1, '{0}', self.change_players),
         ('Graphics: ', 2, conf.GRAPHICS, 0, None, .1, '{0:.1f}', self.change_graphics),
         ('Health: ', 3, conf.CAR_HEALTH_ON, ('off', 'on'), self.change_health),
         ('Health: ', 2, conf.CAR_HEALTH_MULTIPLIER, 0, None, .1, '{0:.1f}', self.change_health, False),
         ('Quit', 1, self.game.quit_backend)
     ))
示例#55
0
文件: title.py 项目: ikn/spaaace
 def draw (self, screen):
     rtn = Level.draw(self, screen)
     # draw options
     w, h = conf.RES
     self.draw_options(screen, (0, 0, w, h), players = self.num_cars,
                       graphics = conf.GRAPHICS)
     return True or rtn
示例#56
0
文件: game.py 项目: nadako/dungeons
 def enter(self):
     self._g_root = greenlet.getcurrent()
     self._g_loop = greenlet.greenlet(self._loop)
     self.message_log = MessageLog()
     self.level = Level(self, self.DUNGEON_SIZE_X, self.DUNGEON_SIZE_Y)
     self.game.window.push_handlers(self)
     self._g_loop.switch()
示例#57
0
文件: game.py 项目: alecgoebel/div2
    def setup(self):
        scr_size = self.app.screen.get_size()

        self.level = Level(scr_size)
        self.level.restart()

        self.cheat_idx = 0

        self.background = TiledImage(load_image("grass"))

        # makes things look a bit nicer for some reason
        w = self.background.rect.width
        self.background.rect.move_ip(-w/2, -w/2)

        self.l_shadow = ShadowLayer(scr_size)
        self.l_sprite = Layer(scr_size)

        self.sprites = Group()

        self.app.scores.reset()

        self.font = pygame.font.Font(None, 60) 

        self.cheating = False

        play_song("maintheme", volume=0.7)
示例#58
0
文件: game.py 项目: saltire/roverchip
 def advance_level():
     # start the next level, or return false if there is none
     self.current_level += 1
     try:
         self.level = Level(self.leveldata[self.current_level])
     except IndexError:
         return False
示例#59
0
文件: game.py 项目: LordHamu/RunNGun
 def load_level(self, level):
     if self.start_level == None:
         self.start_level = level[0]
     self.menu_flag = False
     player_hp = -1
     if hasattr(self, 'player'):
         player_hp = self.player.get_life()
     self.clear()
     self.level = Level(self.main_menu.get_level_json(level[0]))
     if level[1] != 0:
         self.level.player_x = int(level[1])
     if level[2] != 0:
         self.level.player_y = int(level[2])
     self.scenery_sprite_list = self.level.build_scenery()
     self.platform_sprite_list = self.level.build_platforms()
     self.ladder_sprite_list = self.level.build_ladders()
     self.door_sprite_list = self.level.build_doors()
     self.monster_sprite_list = self.level.build_monsters()
     self.spawners = self.level.build_spawners()
     self.backdrop = self.level.backdrop
     self.add_player(self.character, self.level.player_x,
                     self.level.player_y, level[3])
     if player_hp > 0:
         self.player.set_life(player_hp)
     self.add_camera()
     self.add_lifebar(25, 25, 'player', self.player)
     if self.level.boss and not(self.main_menu.boss_check(self.start_level)):
         self.boss = self.level.boss_mob
         self.monster_sprite_list.add(self.boss)
         self.add_lifebar(constants.DWIDTH - 50, 25, 'boss', self.boss)
示例#60
0
 def __init__(self, world_size=WORLD_SIZE):
     self.world_center = Point((world_size // 2, world_size // 2))
     self.world_size = world_size
     self.snake = Snake(start=self.world_center, start_length=SNAKE_START_LENGTH, growth_pending = GROWTH_PENDING)
     self.level = Level(size=self.world_size, snake=self.snake)
     self.score = 0
     self.controller = Controller(self.level.level_render)