Beispiel #1
0
def mouse_handler(pos):
    global level1
    global level2
    global level3
    global level4
    global level5
    global menu
    if not menu.game_start:
        if menu.BUTT_Pos[0] - menu.BUTT_CENTRE[0] <= pos[
                0] <= menu.BUTT_Pos[0] + menu.BUTT_CENTRE[0]:
            if menu.BUTT_Pos[1] - menu.BUTT_CENTRE[1] <= pos[
                    1] <= menu.BUTT_Pos[1] + menu.BUTT_CENTRE[1]:
                level1.LoadLevel()
                menu.game_start = True
    if menu.game_end or menu.won:
        if menu.END_BUTT_Pos[0] - menu.BUTT_CENTRE[0] <= pos[
                0] <= menu.END_BUTT_Pos[0] + menu.BUTT_CENTRE[0]:
            if menu.END_BUTT_Pos[1] - menu.BUTT_CENTRE[1] <= pos[
                    1] <= menu.END_BUTT_Pos[1] + menu.BUTT_CENTRE[1]:
                menu.game_music.pause()
                menu.menu_music.pause()
                menu = Menu()
                Levels.restart()
                level1 = Level1()
                level2 = Level2()
                level3 = Level3()
                level4 = Level4()
                level5 = Level5()
                frame.set_keydown_handler(Levels.kbd.keyDown)
                frame.set_keyup_handler(Levels.kbd.keyUp)
Beispiel #2
0
	def levelup(self):
		if self.level < len(Levels.keys()):
			self.level += 1
		else:
			self.loop()
		self.level_maker.render_level(self.level)
		self.player.spawn()
Beispiel #3
0
    def __init__(self, **kwargs):
        super(Game2048, self).__init__()

        self.levels = Levels()
        self.current_level = self.levels.next_level()
        self.level_info = self.current_level.info
        self.grid_size = self.current_level.grid_size
        self.grid = self.current_level.grid[:]

        # bind keyboard
        Window.bind(on_key_down=self.on_key_down)
        Window.on_keyboard = lambda *x: None

        #schedule clock
        Clock.schedule_interval(self.update_time, 1)
        self.restart()
def completer(txt, state):
    levels = Levels.getInstance()
    words = split_buffer()
    if readline.get_begidx() == readline.get_endidx():
        words.append('')
    matched = lookup_words(levels.completion_tab, words)
    matched.append(None)
    return matched[state]
Beispiel #5
0
def completer(txt,state):
    levels = Levels.getInstance()
    words = split_buffer()
    if readline.get_begidx() == readline.get_endidx():
        words.append('')
    matched = lookup_words(levels.completion_tab,words)
    matched.append(None)
    return matched[state]
Beispiel #6
0
def setup(keySet, resolution):
    hero = Hero({
        "Name": 'Hero',
        "Lvl": 1,
        "Exp": 0,
        "Atk": 3,
        "Def": 4,
        "Stam": 3,
        "Health": 25,
        "ExpPoint": 50,
        "Skills": [],
    })
    curMap = Map()
    level = Levels()
    makeWindow(hero, curMap, level, keySet, resolution)
Beispiel #7
0
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('Breakout!')
        icon = pygame.image.load('images/icon.png')
        pygame.display.set_icon(icon)

        # Initialize game objects
        self.paddle = Paddle(self)
        self.ball = Ball(self)
        self.brick = Brick(self)
        self.bricks = pygame.sprite.Group()

        self.level = Levels()
        self._create_level()

        self.hacks_active = False
        self.game_running = False

        self.play_button = Button(self, 'Play')
Beispiel #8
0
Examples:

    # crm -f stopapp2.cli
    # crm < stopapp2.cli
    # crm resource stop global_www
    # crm status 

    """
    sys.exit(1)


user_prefs = UserPrefs.getInstance()
options = Options.getInstance()
err_buf = ErrorBuffer.getInstance()
vars = Vars.getInstance()
levels = Levels.getInstance()


def run():
    prereqs()
    inp_file = ''

    load_rc(vars.rc_file)

    if not sys.stdin.isatty():
        err_buf.reset_lineno()
        options.batch = True
    else:
        options.interactive = True

    try:
Beispiel #9
0
       
# General graphics
livesImg = graphics.g_player.lives
numbers = [graphics.g_numbers.n0, graphics.g_numbers.n1, graphics.g_numbers.n2, graphics.g_numbers.n3, graphics.g_numbers.n4, graphics.g_numbers.n5, graphics.g_numbers.n6, graphics.g_numbers.n7, graphics.g_numbers.n8, graphics.g_numbers.n9]
impImages = [graphics.g_imps.imp0_0, graphics.g_imps.imp1_0, graphics.g_imps.imp2_0, graphics.g_imps.imp3_0, graphics.g_imps.imp4_0, graphics.g_imps.imp5_0]
levelImages = [[graphics.g_tiles.tile01, graphics.g_teleporters.tele01], [graphics.g_tiles.tile02, graphics.g_teleporters.tele02], [graphics.g_tiles.tile03, graphics.g_teleporters.tele03], [graphics.g_tiles.tile04, graphics.g_teleporters.tele04], [graphics.g_tiles.tile05, graphics.g_teleporters.tele05], [graphics.g_tiles.tile06, graphics.g_teleporters.tele06]]
bullet = graphics.g_enemies.bullet

# Init classes
instructions = Interface()
bg = Background(0, 0)
player = Player(0, 2, -12, 106)
audio = Audio(g_sound)
lvlEnemies = Enemy(0, -20, -20, 0, 0)
bonusItem.append(Drops(-20, -20, 0))
aLevel = Levels([levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)], levelMaps[random.getrandbits(4)]])
levelImps = Imps(-20, -20, impImages[0], 0)
flashText = Text(1, 1, "", True, -5)

tmpImpId = random.getrandbits(2)
impId = tmpImpId + random.getrandbits(2)
if impId > 5:
    impId = 5
#############################################
def update():
    global gameState, levelComplete, movePlayerX, impsOnScreen, impId, rndLevel, bonusItem, playerLives, bonusItemDropRate, score, aLevel, tmpImpId
    global cheatsOn, flashPlayer, flashText, freezeTimer, freezeTimerMax, freezeEnemies, bulletVisible, bulletX, bulletY, bulletDir, bulletSpeed, warpPlayed
    
    # Randomize imps during splash
    if gameState == STATE_MENU:
        # Create the random imps
Beispiel #10
0
pygame.init()

size = width, height = 1600, 900

screen = pygame.display.set_mode(settings.size)

backgrounds = dict()
for i in range(4):
    backgrounds[i] = pygame.image.load(
        os.path.join('images', f'background_{i}.png'))

points = Points()
with open('river_system.txt') as input_file:
    points.read(input_file)

levels = Levels('levels.txt')

power_towers = PowerTowers(screen)
vehicles = Vehicles(screen, points)
destinations = Destinations(screen)
hotels = Hotels(screen)
travellers = Travellers(screen)
flash = Flash(screen)

map = Map(
    screen=screen,
    power_towers=power_towers,
    vehicles=vehicles,
    destinations=destinations,
    hotels=hotels,
    travellers=travellers,
Beispiel #11
0
#!/usr/bin/python
from dnd_classes import DNDClasses
from dnd_races import DNDRaces
from levels import Levels
DND_CLASSES = DNDClasses()
DND_RACES = DNDRaces()
LEVELS = Levels()

class Character(object):
    max_HP = None
    current_HP = None
    current_XP = 0
    next_level_XP = None
    level = 1
    MAX_XP = 1000000
    MAX_LEVEL = 30

    attribute_dictionary = {
      'attribute': "name",
      'baseSave': 0,
      'abilityModifier': 0,
      'magicModifier': 0,
      'miscModifier': 0,
      'temporaryModifier': 0
    }

    ability_scores = {
      'STR': 0,
      'DEX': 0,
      'CON': 0,
      'INT': 0,
Beispiel #12
0
 def get_answer(self):
     self.answer = Levels.generate_answer(self.level)
Beispiel #13
0
    def __init__(self, window_width, window_height):
        print "Seed = " + str(util.get_seed())
        pygame.init()
        pygame.mixer.init()

        self.wood = pygame.mixer.Sound("audio/wood.wav")
        self.stone = pygame.mixer.Sound("audio/stone.wav")
        self.ice = pygame.mixer.Sound("audio/ice.wav")
        self.bleep = pygame.mixer.Sound("audio/bleep.wav")
        self.moss = pygame.mixer.Sound("audio/moss.wav")

        self.mute = False

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

        self.score = 0
        self.currentLevel = 0

        self.shootingBird = []

        self.birdType = 1

        self.running = False
        self.instructions = True
        self.win_screen = False
        self.firing = False
        self.pulling = False
        self.mouse_origin = util.Vec2D(0, 0)
        self.launch_velocity = util.Vec2D(0, 0)

        self.window_width = window_width
        self.window_height = window_height
        self.window = pygame.display.set_mode(
            (self.window_width, self.window_height))

        self.space = pymunk.Space()
        self.space.gravity = 0, 3
        self.space.damping = 1

        def collision(arbiter, space, data):
            if (issubclass(arbiter.shapes[0].body.__class__, Bird)
                    and issubclass(arbiter.shapes[1].body.__class__, Block)):
                bird = arbiter.shapes[0]
                block = arbiter.shapes[1]
            elif (issubclass(arbiter.shapes[0].body.__class__, Block)
                  and issubclass(arbiter.shapes[1].body.__class__, Bird)):
                bird = arbiter.shapes[1]
                block = arbiter.shapes[0]
            else:
                return True

            if issubclass(block.body.__class__, Crate):
                if not self.mute: self.wood.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Ice):
                if not self.mute: self.ice.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Sheep):
                self.score += 100
                if not self.mute: self.wood.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Stone):
                if not self.mute: self.stone.play(0, 400)
                return True
            elif issubclass(block.body.__class__, Moss):
                if not self.mute: self.moss.play(0, 400)
                return True

        h = self.space.add_default_collision_handler()
        h.begin = collision

        self.birds = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.blocks = pygame.sprite.Group()
        self.slingshots = pygame.sprite.Group()

        self.slingshot = Slingshot(util.Vec2D(125, self.window_height - 370),
                                   50, "slingshot")
        self.slingshots.add(self.slingshot)

        self.levels = Levels(window_width, window_height)
Beispiel #14
0
              # start the game
# new_position = (x,y)

player = Player((560,230), windowSurface)
playerGroup = pygame.sprite.RenderPlain(player)


HUB = HUB()
transition = Transition(windowSurface)

my_font = pygame.font.SysFont('Verdana', 15)
dialogbox = DialogBox((440, 51), (255, 255, 204), 
    (102, 0, 0), my_font)


level_maker = Levels()
"""
Level maker is used below to generate all the array of sprites of enemies, rocks, 
doors, and dialog    
"""
rocks_by_level = level_maker.createLevels_Rock()
doors_by_level = level_maker.createLevels_Door()
enemies_by_level = level_maker.createLevels_enemies(windowSurface)
enemies_by_level.append(pygame.sprite.RenderPlain(Wizderp(windowSurface)))
level_background = level_maker.drawBackground(windowSurface)
speech_by_level = level_maker.dialogSelect()
player_entrance = level_maker.playerStartPositions()
plates_by_level = level_maker.placePlate()
downedComp = DownedComp()
throne = Throne()
fpsClock = pygame.time.Clock()
Beispiel #15
0
Examples:

    # crm -f stopapp2.cli
    # crm < stopapp2.cli
    # crm resource stop global_www
    # crm status 

    """
    sys.exit(1)

user_prefs = UserPrefs.getInstance()
options = Options.getInstance()
err_buf = ErrorBuffer.getInstance()
vars = Vars.getInstance()
levels = Levels.getInstance()

def run():
    prereqs()
    inp_file = ''

    load_rc(vars.rc_file)

    if not sys.stdin.isatty():
        err_buf.reset_lineno()
        options.batch = True
    else:
        options.interactive = True

    try:
        opts, args = getopt.getopt(sys.argv[1:], \
Beispiel #16
0
class Game2048(Widget):

    cube_size = NumericProperty(10)
    cube_padding = NumericProperty(10)
    score = NumericProperty(0)
    moves = NumericProperty(0)
    mytime = NumericProperty(0)
    ended = False
    win_value = False
    level_info = StringProperty("")

    def __init__(self, **kwargs):
        super(Game2048, self).__init__()

        self.levels = Levels()
        self.current_level = self.levels.next_level()
        self.level_info = self.current_level.info
        self.grid_size = self.current_level.grid_size
        self.grid = self.current_level.grid[:]

        # bind keyboard
        Window.bind(on_key_down=self.on_key_down)
        Window.on_keyboard = lambda *x: None

        #schedule clock
        Clock.schedule_interval(self.update_time, 1)
        self.restart()

    #######################################################
    #                 Event handlers                      #
    #######################################################

    def on_key_down(self, window, key, *args):
        if key == 273:
            self.move("up")
        elif key == 274:
            self.move("down")
        elif key == 276:
            self.move("right")
        elif key == 275:
            self.move("left")
        elif key == 27 and platform == 'android':
            from jnius import autoclass
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            PythonActivity.mActivity.moveTaskToBack(dTrue)
            return True

        # if game won or lost
        if self.get_game_status() != None:
            self.end()
            self.ended = True

        if (self.has_empty()
                or self.can_combine()) and self.moved and not self.ended:
            Clock.schedule_once(self.spawn_number, .20)

    def on_touch_up(self, touch):
        print("ontouch up")
        v = Vector(touch.pos) - Vector(touch.opos)
        if v.length() < dp(20):
            return

        # detect direction
        dx, dy = v
        if abs(dx) > abs(dy):
            if dx > 0:
                self.move("left")
            else:
                self.move("right")
        else:
            if dy > 0:
                self.move("up")
            else:
                self.move("down")

        # if game won or lost
        if self.get_game_status() != None:
            self.end()
            self.ended = True

        if (self.has_empty()
                or self.can_combine()) and self.moved and not self.ended:
            Clock.schedule_once(self.spawn_number, .20)

        return True

    ##########################################################
    #                   Selectors                            #
    ##########################################################

    def iterate_grid(self, grid):
        for ix in range(len(grid)):
            for iy in range(len(grid)):
                child = grid[ix][iy]
                yield ix, iy, child

    def get_cubes(self):
        cubes = []
        for ix, iy, child in self.iterate_grid(self.grid):
            if child and not (child == "Blocked"):
                cubes.append([ix, iy, child])
        return cubes

    def get_empty(self):
        empty = []
        for ix, iy, child in self.iterate_grid(self.grid):
            if not child:
                empty.append([ix, iy])
        return empty

    def get_cube_pos(self, ix, iy):
        padding = self.cube_padding
        cube_size = self.cube_size
        return [(self.x + padding) + ix * (cube_size + padding),
                (self.y + padding) + iy * (cube_size + padding)]

    def get_game_status(self):
        # check level end
        game_status = self.current_level.check_condition(
            self.get_cubes(), self.score, self.moves, self.mytime)
        return game_status

    def can_combine(self):
        grid = self.grid
        for iy in range(4):
            for ix in range(3):
                cube1 = grid[ix][iy]
                cube2 = grid[ix + 1][iy]
                if cube1.number == cube2.number:
                    return True

        for ix in range(4):
            for iy in range(3):
                cube1 = grid[ix][iy]
                cube2 = grid[ix][iy + 1]
                if cube1.number == cube2.number:
                    return True

    def has_empty(self):
        if len(self.get_empty()) != 0:
            return True
        return False

    ######################################################
    ######################################################

    def build_grid(self):
        self.grid = []
        for i in range(len(self.current_level.grid)):
            self.grid.append([])
            for j in self.current_level.grid[i]:
                self.grid[i].append(j)

    def create_blocked_cubes(self, *args):
        for ix, iy, child in self.iterate_grid(self.grid):
            if child == "Blocked":
                self.grid[ix][iy] = None
                self.spawn_number_at(ix, iy, 1)

    def update_time(self, callback):
        if not self.ended:
            self.mytime = self.mytime + 1

    def rebuild_background(self):
        self.canvas.before.clear()
        with self.canvas.before:
            Color(230 / 255., 230 / 255., 230 / 255.)
            #BorderImage(pos=self.pos, size=self.size, source='data/round.png')
            #Color(60/255., 60/255., 60/255.)
            csize = self.cube_size, self.cube_size
            for ix, iy, child in self.iterate_grid(self.grid):
                BorderImage(pos=self.get_cube_pos(ix, iy),
                            size=csize,
                            source='data/square2.png')

    def reposition(self, *args):
        # calculate the size of a number
        l = min(self.width, self.height)
        padding = (l / float(self.grid_size)) / 8. - 7
        cube_size = (l - (padding * 6)) / float(self.grid_size)
        self.cube_size = cube_size
        self.cube_padding = padding

        self.rebuild_background()

        for i in self.get_cubes():
            i[2].size = cube_size, cube_size
            i[2].pos = self.get_cube_pos(i[0], i[1])

    def spawn_number(self, *args):
        empty = self.get_empty()
        if len(empty) == 0:
            return
        value = 2 if random() < .9 else 4
        maxnum = len(empty) - 1
        random_index = randint(0, maxnum)
        ix = empty[random_index][0]
        iy = empty[random_index][1]
        self.spawn_number_at(ix, iy, value)

    def spawn_number_at(self, ix, iy, value):
        number = Number(size=(self.cube_size, self.cube_size),
                        pos=self.get_cube_pos(ix, iy),
                        number=value)
        self.grid[ix][iy] = number
        print("Number test:", self.grid[ix][iy].number)
        self.add_widget(number)

    def move(self, direction):
        if direction == "left" or direction == "up":
            rng = range(self.grid_size - 1, -1, -1)
        elif direction == "right" or direction == "down":
            rng = range(self.grid_size)

        grid = self.grid
        self.moved = False

        for i in range(self.grid_size):
            # get cubes for the current line
            cubes = []
            # interate from 0=>4 or 4=>0
            for j in rng:
                if direction == "left" or direction == "right":
                    ix = j
                    iy = i
                elif direction == "up" or direction == "down":
                    ix = i
                    iy = j
                cube = self.grid[ix][iy]
                if cube:
                    cubes.append(cube)
            # combine cubes
            self.combine(cubes)

            # update grid
            for j in rng:
                if direction == "left" or direction == "right":
                    ix = j
                    iy = i
                elif direction == "up" or direction == "down":
                    ix = i
                    iy = j

                cube = cubes.pop(0) if cubes else None
                if grid[ix][iy] != cube:
                    self.moved = True
                grid[ix][iy] = cube
                if not cube or cube == "Blocked":
                    continue

                pos = self.get_cube_pos(ix, iy)
                if cube.pos != pos:
                    cube.move_to(pos)

        if not self.ended and self.moved:
            self.moves = self.moves + 1

    def combine(self, cubes):
        if len(cubes) <= 1:
            return cubes
        index = 0
        while index < len(cubes) - 1:
            cube1 = cubes[index]
            cube2 = cubes[index + 1]
            if cube1.number == cube2.number:
                cube1.number *= 2
                if not self.ended:
                    self.score += cube1.number
                cube2.move_to_and_destroy(cube1.pos)
                del cubes[index + 1]

            index += 1

    def end(self):
        end = self.ids.end.__self__
        self.remove_widget(end)
        self.add_widget(end)
        text = ""

        if self.get_game_status() == "won":
            text = "WIN"
            next_level = self.levels.get_next_level()
            next_level.unlocked = True
            next_level.color = "#37988F"
            self.ids.next_level_button.opacity = 1

        elif self.get_game_status() == "lost":
            text = "FAILED"
            self.ids.next_level_button.opacity = 0.5

        self.ids.end_label.text = text
        Animation(opacity=1., d=.5).start(end)
        app.gs_score(self.score)

    def restart(self):
        self.score, self.moves, self.mytime = 0, 0, 0
        self.ended = False
        self.level_info = self.current_level.info
        for i in self.get_cubes():
            i[2].destroy()
        self.ids.levelsgrid.clear_widgets()
        self.grid_size = self.current_level.grid_size
        self.build_grid()
        self.reposition()

        Clock.schedule_once(self.create_blocked_cubes, .1)
        Clock.schedule_once(self.spawn_number, .1)
        Clock.schedule_once(self.spawn_number, .1)
        self.ids.end.opacity = 0
        self.ids.levelspane.opacity = 0

    def next_level(self):
        self.current_level = self.levels.next_level()
        self.level_info = self.current_level.info
        self.restart()

    def all_levels(self):
        levelspane = self.ids.levelspane.__self__
        end = self.ids.end.__self__
        self.remove_widget(levelspane)
        self.ids.end.opacity = 0
        self.remove_widget(end)
        self.add_widget(levelspane)

        ix = 0
        iy = 0
        for lvl_index in range(len(self.levels.levels)):
            level_button = LevelButton(self.levels.levels[lvl_index],
                                       self,
                                       size=(self.cube_size, self.cube_size),
                                       pos=self.get_cube_pos(ix, iy),
                                       number=lvl_index)
            self.ids.levelsgrid.add_widget(level_button)
            ix = ix + 1
            if ix > 5:
                ix = 0
                iy = iy + 1

        self.ids.levelspane.opacity = 1
Beispiel #17
0
def draw(canvas):
    if menu.game_start and not menu.game_end:
        Levels.update()
        Levels.draw(canvas)
    menu.draw(canvas)
    menu.update()
                    break  # Break loop if it reaches level 6.
            window_clear('cls')

        if level_complete:
            print(GAME_OVER)
            print(DOLL_PICTURE[lap_counter])
        else:
            print(GAME_OVER)
            print(DOLL_PICTURE[num_image + 1])

        dashboard(word, formatted_word, string_entered, formatted_string_ent,\
                  found_letters)

        keep_playing = ask_continue_playing(keep_playing, level_complete, word)

    if level_complete:
        print(GAME_OVER)
        print(DOLL_PICTURE[lap_counter])
    else:
        print(GAME_OVER)
        print(DOLL_PICTURE[6])


if __name__ == '__main__':
    LEVEL = Levels().LEVELS
    DOLL_PICTURE = Images().IMAGES
    GAME_OVER = GameOver().GAME_OVER
    WORDS = list_words()
    NUM_OF_WORDS_IN_LIST = len(WORDS) - 1
    main()
Beispiel #19
0
class AngryBirds:
    WINDOW_COLOR = pygame.Color("lightblue")
    LAUNCH_SPEED = .3  # active

    def __init__(self, window_width, window_height):
        print "Seed = " + str(util.get_seed())
        pygame.init()
        pygame.mixer.init()

        self.wood = pygame.mixer.Sound("audio/wood.wav")
        self.stone = pygame.mixer.Sound("audio/stone.wav")
        self.ice = pygame.mixer.Sound("audio/ice.wav")
        self.bleep = pygame.mixer.Sound("audio/bleep.wav")
        self.moss = pygame.mixer.Sound("audio/moss.wav")

        self.mute = False

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

        self.score = 0
        self.currentLevel = 0

        self.shootingBird = []

        self.birdType = 1

        self.running = False
        self.instructions = True
        self.win_screen = False
        self.firing = False
        self.pulling = False
        self.mouse_origin = util.Vec2D(0, 0)
        self.launch_velocity = util.Vec2D(0, 0)

        self.window_width = window_width
        self.window_height = window_height
        self.window = pygame.display.set_mode(
            (self.window_width, self.window_height))

        self.space = pymunk.Space()
        self.space.gravity = 0, 3
        self.space.damping = 1

        def collision(arbiter, space, data):
            if (issubclass(arbiter.shapes[0].body.__class__, Bird)
                    and issubclass(arbiter.shapes[1].body.__class__, Block)):
                bird = arbiter.shapes[0]
                block = arbiter.shapes[1]
            elif (issubclass(arbiter.shapes[0].body.__class__, Block)
                  and issubclass(arbiter.shapes[1].body.__class__, Bird)):
                bird = arbiter.shapes[1]
                block = arbiter.shapes[0]
            else:
                return True

            if issubclass(block.body.__class__, Crate):
                if not self.mute: self.wood.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Ice):
                if not self.mute: self.ice.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Sheep):
                self.score += 100
                if not self.mute: self.wood.play(0, 400)
                space.remove(bird, bird.body)
                space.remove(block, block.body)
                bird.body.kill()
                block.body.kill()
                return False
            elif issubclass(block.body.__class__, Stone):
                if not self.mute: self.stone.play(0, 400)
                return True
            elif issubclass(block.body.__class__, Moss):
                if not self.mute: self.moss.play(0, 400)
                return True

        h = self.space.add_default_collision_handler()
        h.begin = collision

        self.birds = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.blocks = pygame.sprite.Group()
        self.slingshots = pygame.sprite.Group()

        self.slingshot = Slingshot(util.Vec2D(125, self.window_height - 370),
                                   50, "slingshot")
        self.slingshots.add(self.slingshot)

        self.levels = Levels(window_width, window_height)

    def clear_space(self):
        for bird in self.birds:
            self.space.remove(bird.poly)
        for enemy in self.enemies:
            self.space.remove(enemy.poly)
        for block in self.blocks:
            self.space.remove(block.poly)

    def init_level(self, i):
        level = self.levels.get_level(i - 1)

        self.clear_space()
        self.birds = pygame.sprite.Group()
        self.enemies = level.get_enemies()
        self.blocks = level.get_blocks()

        for enemy in self.enemies:
            self.space.add(enemy, enemy.poly)

        for block in self.blocks:
            self.space.add(block, block.poly)

    def run_game(self):
        self.running = True
        while self.running:
            self.tick()
        pygame.quit()

    def tick(self):
        self.handle_events()
        if not self.instructions:
            self.apply_rules()
            self.simulate()
        self.update_display()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_m:
                    self.mute = not self.mute
                elif event.key == pygame.K_SPACE:
                    self.instructions = False
                elif event.key == pygame.K_1:
                    self.instructions = False
                    self.init_level(1)
                elif event.key == pygame.K_2:
                    self.instructions = False
                    self.init_level(2)
                elif event.key == pygame.K_3:
                    self.instructions = False
                    self.init_level(3)
                elif event.key == pygame.K_4:
                    self.instructions = False
                    self.init_level(4)

            elif event.type == pygame.MOUSEBUTTONDOWN:

                #print "Button pressed:", event.dict['button'], "@", event.dict['pos']
                button_pressed = event.dict['button']
                target = event.dict['pos']
                if button_pressed == 1:  # Left click targets
                    self.pulling = True
                    self.mouse_origin = util.Vec2D(target[0], target[1])
                    mouse_end = util.Vec2D(target[0], target[1])
                    self.launch_velocity = self.mouse_origin - mouse_end
                    self.launch_velocity *= AngryBirds.LAUNCH_SPEED

                elif button_pressed == 3:  # Right click fires
                    pass

            elif event.type == pygame.MOUSEBUTTONUP:

                #print "Button released:", event.dict['button'], "@", event.dict['pos']
                button_pressed = event.dict['button']
                target = event.dict['pos']

                if button_pressed == 1:  # Left click targets
                    self.firing = True
                    mouse_end = util.Vec2D(target[0], target[1])
                    self.launch_velocity = self.mouse_origin - mouse_end
                    self.launch_velocity *= AngryBirds.LAUNCH_SPEED
                    #bird.velocity = self.launch_velocity
                    #print self.launch_velocity

                elif button_pressed == 3:  # Right click fires
                    pass

            elif event.type == pygame.MOUSEMOTION:
                target = event.dict['pos']
                mouse_end = util.Vec2D(target[0], target[1])
                self.launch_velocity = self.mouse_origin - mouse_end
                self.launch_velocity *= AngryBirds.LAUNCH_SPEED

    def apply_rules(self):

        if len(self.enemies) == 0:
            self.instructions = False
            self.currentLevel += 1
            self.init_level(self.currentLevel)
            if self.currentLevel == 4:
                self.win_screen = True

        if self.pulling:
            bird = stoneBird(self.slingshot.position.to_tuple(),
                             self.launch_velocity.to_tuple(), "new")
            self.score -= 5
            if self.birdType == 1:
                bird = stoneBird(self.slingshot.position.to_tuple(),
                                 self.launch_velocity.to_tuple(), "new")
                self.birdType = 2
            elif self.birdType == 2:
                bird = iceBird(self.slingshot.position.to_tuple(),
                               self.launch_velocity.to_tuple(), "new")
                self.birdType = 3
            elif self.birdType == 3:
                bird = crateBird(self.slingshot.position.to_tuple(),
                                 self.launch_velocity.to_tuple(), "new")
                self.birdType = 4
            elif self.birdType == 4:
                bird = BasicBird(self.slingshot.position.to_tuple(),
                                 self.launch_velocity.to_tuple(), "new")
                self.birdType = 1

            self.birds.add(bird)
            self.shootingBird.append(bird)
            self.pulling = False

        if len(self.shootingBird) != 0:
            self.shootingBird[0].pullSpot(self.slingshot.position -
                                          self.launch_velocity)

        if self.firing and len(self.shootingBird) != 0:
            self.shootingBird[0].setVel(self.launch_velocity)
            self.space.add(self.shootingBird[0], self.shootingBird[0].poly)
            self.shootingBird = []
            self.firing = False

    def simulate(self):
        self.space.step(0.02)
        for body in self.space.bodies:
            if issubclass(body.__class__, pygame.sprite.Sprite):
                body.update_rect()

    def update_display(self):

        if self.instructions:
            self.window.fill(pygame.Color("green"))
            text_color = pygame.Color("black")
            util.draw_text(self.window, "Angry Birds",
                           (self.window_width / 2, 100), 100, text_color)
            util.draw_text(self.window, "By: Matt & Nik",
                           (self.window_width / 2, 200), 50, text_color)
            util.draw_text(self.window, "Drag to shoot",
                           (self.window_width / 2, 300), 50, text_color)
            util.draw_text(self.window, "Kill all sheep to proceed",
                           (self.window_width / 2, 350), 50, text_color)
            util.draw_text(self.window, "See if you can beat all 3 levels:",
                           (self.window_width / 2, 400), 50, text_color)
            util.draw_text(self.window, "1) The Fortress",
                           (self.window_width / 2, 450), 40, text_color)
            util.draw_text(self.window, "2) Hiding in plain sight",
                           (self.window_width / 2, 500), 40, text_color)
            util.draw_text(self.window, "3) The best defense",
                           (self.window_width / 2, 550), 40, text_color)
            util.draw_text(self.window, "Press space to start",
                           (self.window_width / 2, 700), 50, text_color)

        elif self.win_screen:
            self.window.fill(pygame.Color("blue"))
            util.draw_text(self.window, "You Won!?",
                           (self.window_width / 2, 100), 100,
                           pygame.Color("pink"))
            util.draw_text(self.window, "Your score was: " + str(self.score),
                           (self.window_width / 2, 100), 100,
                           pygame.Color("pink"))
        else:
            self.window.fill(AngryBirds.WINDOW_COLOR)

            what = self.font.render(
                "Level: " + str(self.currentLevel) + "     Score: " +
                str(self.score), True, pygame.Color("Black"))
            self.window.blit(what, (100, 100))
            self.slingshots.draw(self.window)
            self.birds.update(self.window)
            self.enemies.draw(self.window)
            self.blocks.draw(self.window)

        pygame.display.update()

    def label_objects(self):
        for bird in self.birds:
            util.draw_text(self.window, bird.__str__(),
                           bird.get_position().to_tuple(), 24)
Beispiel #20
0
 def get_question(self):
     self.question = Levels.generate_question(self.level)