Пример #1
0
def enter():
    server.boy = Boy()
    game_world.add_object(server.boy, 1)

    server.background = Background()
    game_world.add_object(server.background, 0)
Пример #2
0
 def init_background(self):
     self.ingame_bg = [
         Background("Assets/background/0.png", 0, 0),
         Background("Assets/background/1.png", 0, -850),
         Background("Assets/background/2.png", 0, -1700)
     ]
Пример #3
0
playerDir = (os.path.join(assetsDir, "Player"))

allSprites = pygame.sprite.Group()

cloudImg = pygame.image.load(os.path.join(backgroundDir,
                                          "cloud.png")).convert_alpha()

WHITE = (255, 255, 255)
clock = pygame.time.Clock()
FPS = 30

running = True

player1 = Player(playerDir, WINDOW_SIZE[0], WINDOW_SIZE[1])
enemy1 = Enemy(enemyDir, WINDOW_SIZE[0], WINDOW_SIZE[1])
background = Background(backgroundDir, WINDOW_SIZE[0], WINDOW_SIZE[1])
allSprites.add(background)
allSprites.add(player1)
allSprites.add(enemy1)


def detectEvents():
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()


count = 0


def drawGameWindow():
Пример #4
0
    ctx = Context(atmos, spect, eqPops, background)

    iterate_ctx(ctx)
    return ctx.I


atmosConst = Falc82()
atmosConst.quadrature(5)
atmos = atmosConst.convert_scales()

aSet = RadiativeSet([CaII_atom(), H_6_atom()])
aSet.set_active('Ca')
spect = aSet.compute_wavelength_grid()
eqPops = aSet.compute_eq_pops(atmos)

background = Background(atmos, spect)
ctx = Context(atmos, spect, eqPops, background)

iterate_ctx(ctx)

tempPert = 50 << u.K
Iplus = np.zeros((spect.wavelength.shape[0], atmos.Nspace))
Iminus = np.zeros((spect.wavelength.shape[0], atmos.Nspace))
for k in range(atmos.Nspace):
    Ip = iterate_temperature_perturbation(eqPops['Ca'].n, k,
                                          0.5 * tempPert)[:, -1]
    Im = iterate_temperature_perturbation(eqPops['Ca'].n, k,
                                          -0.5 * tempPert)[:, -1]
    Iplus[:, k] = Ip
    Iminus[:, k] = Im
Пример #5
0
    def __init__(self):
        self.map = Map()
        self.background = Background()

        self.HeroX = self.map.HeroX
        self.HeroY = self.map.HeroY
        self.EndX = self.map.EndX
        self.EndY = self.map.EndY
        self.run_frames = 0
        self.jump_frames = 0
        self.laser_frames = 0

        self.moveX = 4
        self.slowmoveX = 2.3
        self.maxjump = 23 #점프 최대치

        self.moveTime = SDL_GetTicks()
        self.jumpAnimationTime = SDL_GetTicks()
        self.laserTime = 0

        self.CharState = self.RIGHT_STAND
        self.MoveState = self.CLEAR
        self.SwitchNo = -1
        self.DropSpeed = 10
        self.JumpTime = -1
        self.isjump = False

        self.LeftButton = False
        self.RightButton = False
        self.JumpButton = False
        self.Charview = False


        self.stageclear_str = "res/stageclear/Stageclear_x.png"
        self.clearWin = False
        self.clearDir = False
        self.clearTime = 0
        self.clear_frames = 0

        if(Hero.left_stand == None):
            Hero.left_run           = load_image("res/hero/left_run.png")
            Hero.right_run          = load_image("res/hero/right_run.png")

            Hero.left_stand         = load_image("res/hero/left_stand.png")
            Hero.right_stand        = load_image("res/hero/right_stand.png")

            Hero.left_jump          = load_image("res/hero/left_jump.png")
            Hero.right_jump         = load_image("res/hero/right_jump.png")
            Hero.laser              = load_image("res/hero/laser.png")

            Hero.tutorial_image1       = load_image("res/tutorial/tu1.png")
            Hero.tutorial_image2       = load_image("res/tutorial/tu2.png")
            Hero.tutorial_image3       = load_image("res/tutorial/tu3.png")
            Hero.tutorial_image4       = load_image("res/tutorial/tu4.png")

            Hero.jump_sound = load_wav("res/sound/jump.wav")
            Hero.jump_sound.set_volume(32)

            Hero.switch_sound = load_wav("res/sound/switch.wav")
            Hero.switch_sound.set_volume(70)

            Hero.reset_sound = load_wav("res/sound/reset.wav")
            Hero.reset_sound.set_volume(32)
            Hero.reset_sound.play()

            Hero.clear_sound = load_wav("res/sound/clear.wav")
            Hero.clear_sound.set_volume(90)


            Hero.Stageclear_image = [0 for i in range(0, 18)]

            for i in range(0, 18):
                Hero.Stageclear_image[i] = load_image(self.stageclear_str.replace('x', str(i)))
            Hero.clearbg = load_image("res/stageclear/clearbg.png")

        pass
Пример #6
0
    def __init__(self):

        pg.init()  # Initialize pygame
        self.BG_COLOR = (0, 0, 0)  # Set background to black
        self.screen = pg.display.set_mode(
            (Game.WIDTH, Game.HEIGHT))  # Set window dimensions
        pg.display.set_caption('Pac-Man')  # Set name of the game

        # ******************
        # *** Animations ***
        # ******************
        self.CLOCK = pg.time.Clock()  # Universal animation clock

        self.img_index = Timer(3)  # Pac-man Animations
        self.last_img_index = self.img_index.frame_index()

        self.enemy_img_index = Timer(2)  # Enemy Animations
        self.last_enemy_img_index = self.enemy_img_index.frame_index()
        self.enemy_scatter_index = TimerDual(2, 4)

        self.sprite_store = SpriteStore()  # Instance for retrieving sprites

        portal_sprites = []  # Portal Animations
        for sprite in self.sprite_store.portal:  # Fill list with unscaled images
            portal_sprites.append(pg.transform.scale(sprite, (20, 20)))

        self.portal_img_index = Timer(6)

        # ********************
        # *** Game Objects ***
        # ********************
        self.graph = Graph(self)  # Graph (Map) obj

        self.pacman = Pacman(self, self.sprite_store.pacman,
                             self.graph)  # Pac-man obj

        self.portal1 = Portal(self, portal_sprites)  # Portal One obj
        self.portal2 = Portal(self, portal_sprites)  # Portal Two obj
        self.portals = [self.portal1, self.portal2]  # List of Portal obj's

        self.blinky = Enemy(self, self.sprite_store.blinky,
                            self.graph)  # 1. Blinky obj (Enemy00)
        self.pinky = Enemy(self, self.sprite_store.pinky,
                           self.graph)  # 2. Pinky  obj (Enemy01)
        self.clyde = Enemy(self, self.sprite_store.clyde,
                           self.graph)  # 3. Clyde  obj (Enemy02)
        self.inkey = Enemy(self, self.sprite_store.inkey,
                           self.graph)  # 4. Inkey  obj (Enemy03)
        self.enemies = []  # List of Enemy obj's
        self.enemies.append(self.blinky)  # Add enemies to list
        self.enemies.append(self.pinky)
        self.enemies.append(self.clyde)
        self.enemies.append(self.inkey)

        self.bg = Background('images/map.png', (0, 60))  # Background Image obj
        self.small_logo = self.sprite_store.get_small_logo()
        self.big_logo = self.sprite_store.get_bigger_logo()
        # **********************
        # *** Initialization ***
        # **********************
        self.pacman.rect.centerx = self.graph.nodes[
            65].x  # Set Pac-man to node 65
        self.pacman.rect.centery = self.graph.nodes[65].y
        self.pacman.adj_node = self.graph.nodes[65]

        self.initialize_enemies()

        self.pellets = Group()

        for pellet in self.graph.pellets:
            self.pellets.add(pellet)

        self.score = 0
        self.high_score = 0
        self.win = False
        self.last_key = None  # Last key the user inputted

        self.start_screen = True

        self.initial_start = True
        self.is_paused = False
        self.game_over = False
        self.new_life = False
        self.has_game_started = False

        # buttons
        self.play_button = True
        self.play_button_rect = None
        self.hs_show = False
        self.hs_button = True
        self.hs_button_rect = None
        self.back_button = False
        self.back_button_rect = None

        self.last_flip = pg.time.get_ticks()
        self.show = True
        self.debug_game_state()

        # define the RGB value for white,
        #  green, blue colour .
        self.white = (255, 255, 255)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 128)

        # ************************
        # ********* U.I. *********
        # ************************
        self.pac_life_icon = self.sprite_store.pac_life
        self.cherry_icon = self.sprite_store.fruits[0]
        self.sound_icon = pg.image.load(r'images/sound_icon.png')

        self.load_high_score()  # Load high scores
        # ************************
        # ******** Sounds ********
        # ************************
        pg.mixer.init()

        # If you want more channels, change 8 to a desired number. 8 is the default number of channel

        pg.mixer.set_num_channels(8)
        self.voice = pg.mixer.Channel(5)
        self.portal = pg.mixer.Channel(6)

        # This is the sound channel
        self.eating_sound = pg.mixer.Sound('sounds/chomp.wav')
        self.death_sound = pg.mixer.Sound('sounds/pacman_death.wav')
        self.beginning_music = pg.mixer.Sound('sounds/beginning.wav')
        self.portal_shoot = pg.mixer.Sound('sounds/portal_shoot.wav')
        self.tp_sound = pg.mixer.Sound('sounds/tp.wav')
        self.eat_ghost_sound = pg.mixer.Sound('sounds/pacman_eat_ghost.wav')
        pg.mixer.music.load('sounds/pkmn_trainer_victory_cut_for_loop.wav')

        spac_imgs = self.sprite_store.get_pacman_sprites(
        )  # L indices -- 0, 1, 2 // R indices -- 0, 3, 4
        self.starter_pacman = []
        for img in spac_imgs:
            self.starter_pacman.append(pg.transform.scale(img, (48, 48)))
        self.starter_pacman_rect = self.starter_pacman[0].get_rect()
        self.starter_pacman_rect.centerx = -48
        self.starter_pacman_rect.centery = 430

        # ALL GHOSTS: L indices -- 4, 5 // R indices -- 0, 1
        sblinky_imgs = self.sprite_store.get_blinky_sprites()
        self.starter_blinky = []
        for img in sblinky_imgs:
            self.starter_blinky.append(pg.transform.scale(img, (48, 48)))
        self.starter_blinky_rect = self.starter_blinky[0].get_rect()
        self.starter_blinky_rect.centerx = -144
        self.starter_blinky_rect.centery = 430

        spinky_imgs = self.sprite_store.get_pinky_sprites()
        self.starter_pinky = []
        for img in spinky_imgs:
            self.starter_pinky.append(pg.transform.scale(img, (48, 48)))
        self.starter_pinky_rect = self.starter_pinky[0].get_rect()
        self.starter_pinky_rect.centerx = -199
        self.starter_pinky_rect.centery = 430

        sclyde_imgs = self.sprite_store.get_clyde_sprites()
        self.starter_clyde = []
        for img in sclyde_imgs:
            self.starter_clyde.append(pg.transform.scale(img, (48, 48)))
        self.starter_clyde_rect = self.starter_clyde[0].get_rect()
        self.starter_clyde_rect.centerx = -254
        self.starter_clyde_rect.centery = 430

        sinkey_imgs = self.sprite_store.get_inkey_sprites()
        self.starter_inkey = []
        for img in sinkey_imgs:
            self.starter_inkey.append(pg.transform.scale(img, (48, 48)))
        self.starter_inkey_rect = self.starter_inkey[0].get_rect()
        self.starter_inkey_rect.centerx = -309
        self.starter_inkey_rect.centery = 430

        running_away = self.sprite_store.get_ghost_running_away_sprites()
        self.starter_running_away = []
        for img in running_away:
            self.starter_running_away.append(pg.transform.scale(img, (48, 48)))

        self.starter_entities = []
        self.starter_entities.append(
            [self.starter_blinky, self.starter_blinky_rect])
        self.starter_entities.append(
            [self.starter_pinky, self.starter_pinky_rect])
        self.starter_entities.append(
            [self.starter_clyde, self.starter_clyde_rect])
        self.starter_entities.append(
            [self.starter_inkey, self.starter_inkey_rect])

        self.starter_right = True
Пример #7
0
def show_menu():
    global new_game, captured_char, gameplay, list_of_chars, split_mode_on, str_to_disp, game_start
    game_start = True
    BackGround = Background('./assets/images/background_image.png', [0, 0])
    screen.fill([255, 255, 255])
    screen.blit(BackGround.image, BackGround.rect)

    events = pygame.event.get()
    str_to_disp = ''
    split_mode_on = False
    for event in events:
        if event.type == pygame.QUIT:
            exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                new_game = not new_game
                pygame.mixer.music.play()

            elif event.key == pygame.K_RETURN:
                if new_game:
                    captured_char = []
                else:
                    try:
                        fp = open("savefile_char", "rb")
                        captured_char = pickle.load(fp)
                        fp.close()
                    except:
                        captured_char = []

                    try:
                        fp = open("savefile_split", "rb")
                        split_mode_on = pickle.load(fp)
                        fp.close()
                    except:
                        split_mode_on = False
                gameplay = not gameplay
                list_of_chars = [char_text.char_text(gc(captured_char))]
                return ()
    titlebasicfont = pygame.font.SysFont(None, (variables.screen_max_y) // 5)
    titleText = titlebasicfont.render('Space _ B___ars', True, (0, 255, 250))
    titleTextrect = titleText.get_rect()
    titleTextrect.centerx = variables.screen_max_x // 2
    titleTextrect.centery = variables.screen_max_y // 4
    screen.blit(titleText, titleTextrect)
    menubasicfont = pygame.font.SysFont(None, (variables.screen_max_y) // 10)
    menuText1 = menubasicfont.render('New Game', True, (101, 115, 126))
    menuText1rect = menuText1.get_rect()
    menuText1rect.centerx = variables.screen_max_x // 2
    menuText1rect.centery = variables.screen_max_y // 2 + variables.screen_max_y // 5
    screen.blit(menuText1, menuText1rect)
    menuText2 = menubasicfont.render('Load Game', True, (101, 115, 126))
    menuText2rect = menuText2.get_rect()
    menuText2rect.centerx = variables.screen_max_x // 2
    menuText2rect.centery = variables.screen_max_y // 2 + (
        3 * variables.screen_max_y) // 10
    screen.blit(menuText2, menuText2rect)

    selector_menu = pygame.Surface(
        (variables.screen_max_x // 2, variables.screen_max_y // 10),
        pygame.SRCALPHA)  # per-pixel alpha
    selector_menu.fill(
        (255, 255, 255, 50))  # notice the alpha value in the color
    if new_game:
        screen.blit(selector_menu,
                    (variables.screen_max_x // 4, variables.screen_max_y // 2 +
                     variables.screen_max_y // 7))
    else:
        screen.blit(selector_menu,
                    (variables.screen_max_x // 4, variables.screen_max_y // 2 +
                     (2 * variables.screen_max_y) // 8))
    pygame.display.update()
Пример #8
0
def main():
    pygame.init()
    #set the display (window)
    DISPLAY = pygame.display.set_mode((640, 480), 0, 32)
    pygame.display.set_caption('Steven Jump')
    #get fonts
    font = pygame.font.Font('assets/fonts/font.otf', 100)
    font_small = pygame.font.Font('assets/fonts/font.otf', 32)
    font_20 = pygame.font.Font('assets/fonts/font.otf', 20)
    #get images
    shop = pygame.image.load('assets/gfx/shop2.png')
    shop_bg = pygame.image.load('assets/gfx/shop_bg.png')
    retry_button = pygame.image.load('assets/gfx/retry_button.png')
    logo = pygame.image.load('assets/gfx/logostjump2.png')
    title_bg = pygame.image.load('assets/gfx/bg.png')
    title_bg.fill((255, 30.599999999999998, 0.0),
                  special_flags=pygame.BLEND_ADD)
    #get sounds
    flapfx = pygame.mixer.Sound("assets/sfx/flap.wav")
    upgradefx = pygame.mixer.Sound("assets/sfx/upgrade.wav")
    beanfx = pygame.mixer.Sound("assets/sfx/bone2.wav")
    deadfx = pygame.mixer.Sound("assets/sfx/dead2.wav")
    # colors
    WHITE = (255, 255, 255)  # constant
    # variables
    rotOffset = -5
    # creating a new object player
    player = Player()
    bones = []
    buttons = []
    # adding three buttons
    for i in range(3):
        buttons.append(Button())
    # now simply loading images based off of indexes in the list
    buttons[0].typeIndicatorSprite = pygame.image.load(
        'assets/gfx/flap_indicator.png')
    buttons[0].price = 5
    buttons[1].typeIndicatorSprite = pygame.image.load(
        'assets/gfx/speed_indicator.png')
    buttons[1].price = 5
    buttons[2].typeIndicatorSprite = pygame.image.load(
        'assets/gfx/boneup_indicator.png')
    buttons[2].price = 30
    # getting 5 beans
    for i in range(5):
        bones.append(Bone())
    # now looping through the beans list
    for bone in bones:
        bone.position.xy = random.randrange(
            0,
            DISPLAY.get_width() - bone.sprite.get_width()
        ), bones.index(bone) * -200 - player.position.y
    # creating a list of backgrounds, with each index being an object
    bg = [Background(), Background(), Background()]
    # some variables that we need
    beanCount = 0
    startingHeight = player.position.y
    height = 0
    health = 100
    flapForce = 3
    beanMultiplier = 5
    dead = False
    # we need the framerate and then the time
    framerate = 60
    last_time = time.time()
    splashScreenTimer = 0
    #splash screen
    # playing a sound
    pygame.mixer.Sound.play(flapfx)
    while splashScreenTimer < 100:
        dt = time.time() - last_time
        dt *= 60
        last_time = time.time()

        splashScreenTimer += dt

        for event in pygame.event.get():
            # if the user clicks the button
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        DISPLAY.fill((231, 205, 183))
        # fill the start message on the top of the game
        startMessage = font_small.render("PIOTROZA", True, (171, 145, 123))
        DISPLAY.blit(
            startMessage,
            (DISPLAY.get_width() / 2 - startMessage.get_width() / 2,
             DISPLAY.get_height() / 2 - startMessage.get_height() / 2))

        # update display
        pygame.display.update()
        # wait for 10 seconds
        pygame.time.delay(10)

    titleScreen = True
    # title screen
    pygame.mixer.Sound.play(flapfx)
    while titleScreen:
        dt = time.time() - last_time
        dt *= 60
        last_time = time.time()
        # get the position of the mouse
        mouseX, mouseY = pygame.mouse.get_pos()
        # getting the keys pressed
        clicked = False
        keys = pygame.key.get_pressed()
        # checking events
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                clicked = True
            # if the player quits
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        # so the user clicked, and by any change the mouse's position was on the buttons
        if (clicked and checkCollisions(
                mouseX, mouseY, 3, 3,
                DISPLAY.get_width() / 2 - retry_button.get_width() / 2, 288,
                retry_button.get_width(), retry_button.get_height())):
            clicked = False
            pygame.mixer.Sound.play(upgradefx)
            titleScreen = False

        DISPLAY.fill(WHITE)
        DISPLAY.blit(title_bg, (0, 0))
        DISPLAY.blit(logo, (DISPLAY.get_width() / 2 - logo.get_width() / 2,
                            DISPLAY.get_height() / 2 - logo.get_height() / 2 +
                            math.sin(time.time() * 5) * 5 - 25))
        DISPLAY.blit(
            retry_button,
            (DISPLAY.get_width() / 2 - retry_button.get_width() / 2, 288))
        startMessage = font_small.render("START", True, (0, 0, 0))
        DISPLAY.blit(
            startMessage,
            (DISPLAY.get_width() / 2 - startMessage.get_width() / 2, 292))

        pygame.display.update()
        pygame.time.delay(10)

    # the main game loop
    while True:
        dt = time.time() - last_time
        dt *= 60
        last_time = time.time()
        # again, get the position
        mouseX, mouseY = pygame.mouse.get_pos()

        jump = False
        clicked = False
        keys = pygame.key.get_pressed()
        # get events
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and event.key == K_SPACE:
                jump = True
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                clicked = True
            if clicked and mouseY < DISPLAY.get_height() - 90:
                jump = True
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        camOffset = -player.position.y + DISPLAY.get_height(
        ) / 2 - player.currentSprite.get_size()[1] / 2

        DISPLAY.fill(WHITE)
        for o in bg:
            o.setSprite(((player.position.y / 50) % 100) / 100)
            DISPLAY.blit(o.sprite, (0, o.position))

        color = colorsys.hsv_to_rgb(((player.position.y / 50) % 100) / 100,
                                    0.5, 0.5)
        currentHeightMarker = font.render(
            str(height), True,
            (color[0] * 255, color[1] * 255, color[2] * 255, 50))
        DISPLAY.blit(
            currentHeightMarker,
            (DISPLAY.get_width() / 2 - currentHeightMarker.get_width() / 2,
             camOffset + round(
                 (player.position.y - startingHeight) / DISPLAY.get_height()) *
             DISPLAY.get_height() + player.currentSprite.get_height() - 40))

        for bone in bones:
            DISPLAY.blit(bone.sprite,
                         (bone.position.x, bone.position.y + camOffset))

        DISPLAY.blit(
            pygame.transform.rotate(
                player.currentSprite,
                clamp(player.velocity.y, -10, 5) * rotOffset),
            (player.position.x, player.position.y + camOffset))
        DISPLAY.blit(shop_bg, (0, 0))
        pygame.draw.rect(DISPLAY, (81, 48, 20),
                         (21, 437, 150 * (health / 100), 25))
        DISPLAY.blit(shop, (0, 0))

        for button in buttons:
            DISPLAY.blit(button.sprite,
                         (220 + (buttons.index(button) * 125), 393))
            priceDisplay = font_small.render(str(button.price), True,
                                             (0, 0, 0))
            DISPLAY.blit(priceDisplay,
                         (262 + (buttons.index(button) * 125), 408))
            levelDisplay = font_20.render('Lvl. ' + str(button.level), True,
                                          (200, 200, 200))
            DISPLAY.blit(levelDisplay,
                         (234 + (buttons.index(button) * 125), 441))
            DISPLAY.blit(button.typeIndicatorSprite,
                         (202 + (buttons.index(button) * 125), 377))
        beanCountDisplay = font_small.render(
            str(beanCount).zfill(7), True, (0, 0, 0))
        DISPLAY.blit(beanCountDisplay, (72, 394))
        if dead:
            DISPLAY.blit(retry_button, (4, 4))
            deathMessage = font_small.render("RETRY", True, (0, 0, 0))
            DISPLAY.blit(deathMessage, (24, 8))

        height = round(-(player.position.y - startingHeight) /
                       DISPLAY.get_height())

        player.position.x += player.velocity.x * dt
        if player.position.x + player.currentSprite.get_size()[0] > 640:
            player.velocity.x = -abs(player.velocity.x)
            player.currentSprite = player.leftSprite
            rotOffset = 5
        if player.position.x < 0:
            player.velocity.x = abs(player.velocity.x)
            player.currentSprite = player.rightSprite
            rotOffset = -5
        if jump and not dead:
            player.velocity.y = -flapForce
            pygame.mixer.Sound.play(flapfx)
        player.position.y += player.velocity.y * dt
        player.velocity.y = clamp(player.velocity.y + player.acceleration * dt,
                                  -99999999999, 50)

        health -= 0.2 * dt
        if health <= 0 and not dead:
            dead = True
            pygame.mixer.Sound.play(deadfx)

        for bone in bones:
            if bone.position.y + camOffset + 90 > DISPLAY.get_height():
                bone.position.y -= DISPLAY.get_height() * 2
                bone.position.x = random.randrange(
                    0,
                    DISPLAY.get_width() - bone.sprite.get_width())
            if (checkCollisions(player.position.x, player.position.y,
                                player.currentSprite.get_width(),
                                player.currentSprite.get_height(),
                                bone.position.x, bone.position.y,
                                bone.sprite.get_width(),
                                bone.sprite.get_height())):
                dead = False
                pygame.mixer.Sound.play(beanfx)
                beanCount += 1
                health = 100
                bone.position.y -= DISPLAY.get_height() - random.randrange(
                    0, 200)
                bone.position.x = random.randrange(
                    0,
                    DISPLAY.get_width() - bone.sprite.get_width())

        for button in buttons:
            buttonX, buttonY = 220 + (buttons.index(button) * 125), 393
            if clicked and not dead and checkCollisions(
                    mouseX, mouseY, 3, 3, buttonX, buttonY,
                    button.sprite.get_width(), button.sprite.get_height()):
                if (beanCount >= button.price):
                    pygame.mixer.Sound.play(upgradefx)
                    button.level += 1
                    beanCount -= button.price
                    button.price = round(button.price * 2.5)
                    if (buttons.index(button) == 0):
                        flapForce *= 1.5
                    if (buttons.index(button) == 1):
                        player.velocity.x *= 1.5
                    if (buttons.index(button) == 2):
                        oldBeanMultipler = beanMultiplier
                        beanMultiplier += 10
                        for i in range(beanMultiplier):
                            bones.append(Bone())
                            bones[-1].position.xy = random.randrange(
                                0,
                                DISPLAY.get_width() - bone.sprite.get_width()
                            ), player.position.y - DISPLAY.get_height(
                            ) - random.randrange(0, 200)

        if dead and clicked and checkCollisions(mouseX, mouseY, 3, 3, 4, 4,
                                                retry_button.get_width(),
                                                retry_button.get_height()):
            health = 100
            player.velocity.xy = 3, 0
            player.position.xy = 295, 100
            player.currentSprite = player.rightSprite
            beanCount = 0
            height = 0
            flapForce = 3
            beanMultiplier = 5
            buttons = []
            for i in range(3):
                buttons.append(Button())
            buttons[0].typeIndicatorSprite = pygame.image.load(
                'data/gfx/flap_indicator.png')
            buttons[0].price = 5
            buttons[1].typeIndicatorSprite = pygame.image.load(
                'data/gfx/speed_indicator.png')
            buttons[1].price = 5
            buttons[2].typeIndicatorSprite = pygame.image.load(
                'data/gfx/beanup_indicator.png')
            buttons[2].price = 30
            beans = []
            for i in range(5):
                bones.append(Bone())
            for bone in bones:
                bone.position.xy = random.randrange(
                    0,
                    DISPLAY.get_width() - bone.sprite.get_width()
                ), bones.index(bone) * -200 - player.position.y
            pygame.mixer.Sound.play(upgradefx)
            dead = False

        bg[0].position = camOffset + round(
            player.position.y / DISPLAY.get_height()) * DISPLAY.get_height()
        bg[1].position = bg[0].position + DISPLAY.get_height()
        bg[2].position = bg[0].position - DISPLAY.get_height()

        pygame.display.update()
        pygame.time.delay(10)
Пример #9
0
def run_game():

    #Create some groups of objects
    game_objects = Group()
    bullets = Group()
    aliens = Group()
    buttons = Group()
    
    #Initialize game settings
    game_settings = Settings()
    
    #Initialize game statistics
    game_stats = Stats()
    
    #Pygame initiation, and establish screen  
    pygame.init()
    screen = pygame.display.set_mode((game_settings.screen_width, 
                        game_settings.screen_height))
    pygame.display.set_caption(game_settings.screen_title)
    
    #Create background object
    background = Background(screen, game_settings)
    game_objects.add(background)
    
    #Create ship object
    ship = Ship(screen, game_settings)
    game_objects.add(ship)
    
    #Create fleet of aliens then add them to game objects and aliens groups
    gf.create_fleet(screen, game_settings, game_objects, aliens)
    
    #Create buttons then ass them to game_objects and buttons groups
    gf.create_start_buttons(screen, game_settings, game_objects, buttons)
    
    #Create clock object
    clock = Clock()
    
    #Some statistics labels
    level = Label(screen, "level: " + str(game_stats.level), 10, 10)
    game_objects.add(level)

    ammo = Label(screen, "ammo: " + str(ship.game_settings.ammo), 200, 10)
    game_objects.add(ammo)

    points = Label(screen, "score: " + str(game_stats.points), 400, 10)
    game_objects.add(points)

    #Update screen           
    gf.update_screen(game_objects)

    while True:
        if len(aliens) == 0:
            game_stats.level += 1
            game_settings.alien_speed_factor += 1
            game_settings.ammo = game_settings.ammo + game_settings.initial_ammo
            #Create fleet of aliens then add them to game objects and aliens groups
            gf.create_fleet(screen, game_settings, game_objects, aliens)
        
        #Check events key down or key up
        gf.check_events(game_stats, game_objects, ship, bullets, buttons)
    
        level.text = "level: " + str(game_stats.level)
        ammo.text = "ammo: " + str(ship.game_settings.ammo)
        points.text = "score: " + str(game_stats.points)
        
        if game_stats.game_started:
            #Check collisions
            gf.check_collisions(screen, game_settings, game_stats, game_objects, ship, aliens, bullets, buttons)
        
            #Update screen           
            gf.update_screen(game_objects)

        #Wait certain time to achieve 40fps 
        clock.tick(40)
Пример #10
0
 def create_background(self):
     layer = self.level_info.layer
     background = Background(layer)
     return background.get_background()
Пример #11
0
    def __init__(self, fps):
        # load variables
        self.FPS = fps
        self.wind = random.randint(-5, 5) / 100

        #Initialize Everything
        pygame.init()
        self.screen = pygame.display.set_mode((self.MAX_X, self.MAX_Y))
        pygame.display.set_caption('Throw the Kuchen')
        pygame.mouse.set_visible(0)

        #Create The Backgound
        self.background = Background("bg.png")

        #Display The self.background
        self.background.draw(self.screen)
        pygame.display.flip()

        #Prepare Game Objects
        self.clock = pygame.time.Clock()
        whiff_sound = load_sound('whiff.wav')
        punch_sound = load_sound('punch.wav')
        self.snowItems = []
        self.manageSnow()
        self.snowSprites = pygame.sprite.RenderPlain((self.snowItems))

        self.playerItems = []
        # TODO: correct the - 20 on the class itself
        self.player1 = Item(0, self.MAX_Y - 20, "player1.png")
        self.playerItems.append(self.player1)
        self.player2 = Item(self.MAX_X - 20, self.MAX_Y - 20, "player2.png")
        self.playerItems.append(self.player2)
        self.playerSprites = pygame.sprite.RenderPlain((self.playerItems))

        self.kuchenItems = []
        self.kuchen = Item(15, self.MAX_Y - 15, "kuchen.png")
        self.kuchenItems.append(self.kuchen)
        self.kuchenSprites = pygame.sprite.RenderPlain((self.kuchenItems))

        self.uiItems = []
        self.txtWindTitle = UiTxt((self.CENTER_X, 5), " WIND:",
                                  "txtStaticTitle", "center")
        self.uiItems.append(self.txtWindTitle)
        self.txtWind = UiTxt((self.CENTER_X, 20), self.wind, "txtWind",
                             "center")
        self.uiItems.append(self.txtWind)
        p1_pos = self.player1.get_pos()
        new_pos = (p1_pos[0] + 150, p1_pos[1] - 100)

        self.txtForceTitle = UiTxt(new_pos, " FORCE:", "txtStaticTitle",
                                   "center")
        self.uiItems.append(self.txtForceTitle)
        self.txtForce = UiTxt((new_pos[0], new_pos[1] + 15),
                              (self.player1_force, 0, 24), "txtForce",
                              "center")
        self.uiItems.append(self.txtForce)
        self.txtAngleTitle = UiTxt((new_pos[0], new_pos[1] + 50), " ANGLE:",
                                   "txtStaticTitle", "center")
        self.uiItems.append(self.txtAngleTitle)
        self.txtAngle = UiTxt((new_pos[0], new_pos[1] + 65),
                              (self.player1_angle, 0, 90), "txtAngle",
                              "center")
        self.uiItems.append(self.txtAngle)
Пример #12
0
def create_world():
    global boy, background
    boy = Boy()
    background = Background(background_width,background_height)
Пример #13
0
def enter():
    global player, life, scoreStatic, scoreLabel
    bg = Background()
    game_world.add_object(bg, game_world.layer_bg)
    player = Player()
    game_world.add_object(player, game_world.layer_player)
    life = Life()

    global ball
    ball = Ball(400, 400, 1, 1)
    game_world.add_object(ball, game_world.layer_player)

    global wall
    wall = Wall()
    game_world.add_object(wall, game_world.layer_bg)
    bg.target = player

    global stage_number
    stage_number = 1

    cw = get_canvas_width()
    ch = get_canvas_height()

    label = ui.Label("Score:", cw - 200, ch - 55, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    scoreStatic = label

    label = ui.Label("0", cw - 200, ch - 100, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    scoreLabel = label

    global stageStatic, stageLabel
    label = ui.Label("Stage:", cw - 200, ch - 155, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    stageStatic = label

    label = ui.Label("1", cw - 200, ch - 200, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    stageLabel = label

    global bgStatic, bgLabel
    label = ui.Label("BG Idx:", cw - 200, ch - 255, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    bgStatic = label

    label = ui.Label("1", cw - 200, ch - 300, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    bgLabel = label

    global nameStatic, nameLabel
    label = ui.Label("Designer:", cw - 220, ch - 350, 30, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    nameStatic = label

    label = ui.Label("", cw - 190, ch - 400, 36, ui.FONT_2)
    label.color = (255, 191, 127)
    ui.labels.append(label)
    nameLabel = label

    global highscore
    highscore = Highscore()

    global music_bg, wav_bomb, wav_item
    # music_bg = load_music('background.mp3')
    # wav_bomb = load_wav('explosion.wav')
    # wav_item = load_wav('item.wav')

    game_world.isPaused = isPaused

    ready_game()

    global gameOverImage
def run_game():
    global score#enable the "score" variable to be called from inside the function
    pygame.init()#initialize pygame module as the run_game function is started
    settings    = Setting()#import settings and make an instance of setting
    #import the screen width and height from settings module
    screen      = pygame. display.set_mode((settings.screen_width,settings.screen_height))

    #make an empty group to hold all sprites in game
    bullets     = Group()
    ebullets    = Group()
    tornados    = Group()

    #####################################################################
    #__import each modules and make an instance of each related module__#
    #####################################################################
    stats   = GameStats(settings)
    chara   = Chara(settings,screen)
    enemy   = Enemy(settings,screen)
    #first background's x and y position is set 0, thus appear before the second background
    bg1 = Background(0,0,settings,screen)
    #second background's x position is set next to the first background
    bg2 = Background(1300,0,settings,screen)
    bgt = Background(0,0,settings,screen)#instance of the title screen background
    sb  = Scoreboard(settings,screen,stats)#instance of the scoreboard
    #make an instance of the play button, the "PLAY" string is used for the button to be clicked
    #while the "High score" is used to display the high score and calls the global variable of "score"
    play_button = Button(screen, "PLAY", "High Score : " + str(score))#instance of the play button

    ########################################
    #___caption,music file, and booleans___#
    ########################################
    pygame.display.set_caption("Cuphead")#set the programs caption while running
    pygame.mixer.music.load("panic.mp3")#load the music in mp3 format
    pygame.mixer.music.set_volume(0.5)#sets the music volume
    music = 0#acts as the boolean of the music player
    title = 1#sets boolean of the title screen

    ##########################################################
    #____function to display the title screen of the game____#
    ##########################################################
    def main_menu():
        #the title screen is dispalyed right after running the game and when the game is not active
        if title == 1 and stats.game_active == False:
            bgt.blitme2()#displays the background title image
        #check list of events in the game function and perform tasks depending on the type of event which occured
        gf.check_events(settings,screen,stats,chara,bullets,enemy,ebullets,tornados,play_button)
        gf.play_button(stats,play_button)#displays the play button if the game is not active yet

    ##############################################################################
    #___contains event loop and code which manages the game and performs tasks___#
    ##############################################################################
    while True:
        main_menu()#calls the main_menu function

        #performs condition checking after the play button is pressed
        if stats.game_active:
            title = 0#disable the title screen
            if music == 0:
                pygame.mixer.music.play()#plays the music
                music = 1#change music from 0 to 1 to plays the music after the game is set to active

            #displays the first and second background on screen
            screen.blit(bg1.image,bg1.rect)
            screen.blit(bg2.image,bg2.rect)

            gf.check_col(chara, enemy)  # check the collision of chara and enemy

            #updates every module that needed to keep being updated while the game is running
            gf.update_sprites(chara,enemy)
            gf.update_bullets(chara,enemy,bullets,stats,settings,sb)
            gf.update_ebullets(chara,ebullets)
            gf.update_tornados(chara,tornados)
            gf.update_screen(chara,enemy,bullets,ebullets,tornados,sb)

            #update background to move
            bg1.update()#update the first background
            bg2.update()#update the scond background

            ################################################
            #_____conditions while the game is running_____#
            ################### #############################
            #set new high score if the last game score is higher than the current high score
            if stats.score > score and chara.lives_left == 0:
                # rounds up the new high score to the nearest ten and separate it with a comma
                score = "{:,}".format(int(round(stats.score, -1)))

            #to restart the game everytime the player runs out of lives
            if chara.lives_left == 0:
                pygame.mouse.set_visible(True)#set the mouse cursor to be visible
                run_game()#restart the game

        pygame.display.flip()#make the most recently drawn screen be visible
Пример #15
0
musicPlaying = False                    # Toggle for music
flashTextTimer = 60                     # On-screen text timer
highscore = 500                         # Default highscore
shakeX = 0
health = 10                             # Health of ship
bulletCount = 9
bombs = 0                               # Bombs for player emergencies
gameMode = 0                            # 0 for arcade, 1 for survival
# Counters
shuttleTimer = 200
enemyTimer = 400
bossTimer = 500

# Init classes
instructions = Instructions()
bg = Background(0, 0)
player = Player(playerPos[0], playerPos[1], 0, 94, 0, 71)
audio = Audio(g_sound, isThisRealHardware)
shake = Shake()

# Sprites, images, objects
bg = graphics.g_background.bg
logo = graphics.g_items.logo
scoreChars = [graphics.g_numbers.number0, graphics.g_numbers.number1, graphics.g_numbers.number2, graphics.g_numbers.number3, graphics.g_numbers.number4, graphics.g_numbers.number5, graphics.g_numbers.number6, graphics.g_numbers.number7, graphics.g_numbers.number8, graphics.g_numbers.number9]
rockImages = [graphics.g_rocks.rock01, graphics.g_rocks.rock02, graphics.g_rocks.rock03, graphics.g_rocks.rock04, graphics.g_rocks.rock05]
crystalImages = [graphics.g_items.crystal01, graphics.g_items.crystal02, graphics.g_items.crystal03, graphics.g_items.crystal04, graphics.g_items.crystal05, graphics.g_items.crystal06]
playerShip = graphics.g_ships.playerShip
shuttleShip = graphics.g_ships.ship04
enemyShipImages = [graphics.g_ships.ship01, graphics.g_ships.ship02, graphics.g_ships.ship03]
bossShipImages = [graphics.g_ships.boss01, graphics.g_ships.boss02, graphics.g_ships.boss03, graphics.g_ships.boss04]
explosionFrames = [graphics.g_explosion.explode01, graphics.g_explosion.explode02, graphics.g_explosion.explode03, graphics.g_explosion.explode04, graphics.g_explosion.explode05, graphics.g_explosion.explode06, graphics.g_explosion.explode07, graphics.g_explosion.explode08, graphics.g_explosion.explode09, graphics.g_explosion.explode10, graphics.g_explosion.explode11]
Пример #16
0
# Instructor	: Alireza Karduni	#
# Stuent		: Jarrod Norris		#
#####################################

import turtle
from structure import Structure
from background import Background
# Sets a screen for the app to run in
turtle.setup(width=1900, height=1060, startx=0, starty=0)
w = turtle.Screen()

w.title("Fort Norris")
# Sets the colormode for working with rgb
w.colormode(255)
#Sets background color
b1 = Background(w.window_width(), (w.window_height() - 660), "#80e5ff", -950,
                530)
b1.drawSquare()
b2 = Background(w.window_width(), (w.window_height() - 400), "#008000", -950,
                130)
b2.drawSquare()

nw = Structure(-475, 255, "nw")
nw.drawRoof()
nw.drawTower()

ne = Structure(475, 255, "ne")
ne.drawRoof()
ne.drawTower()

sw = Structure(-375, -200, "sw")
sw.drawRoof()
Пример #17
0
def run_game():
    # Initialize pygame
    pygame.init()
    # Initialize pygame mixer
    pygame.mixer.init()

    # Initializing all the game classes.
    ai_settings = Settings()
    stats = GameStats(ai_settings)
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Plain Planes")

    bg = Background(ai_settings, screen)
    sb = Scoreboard(ai_settings, screen, stats)
    ship = Ship(ai_settings, screen, sb)
    gameclock = GameClock(ai_settings, screen)

    # Initializes all the sound classes.
    shipbullet_sounds = ShipBulletSounds()
    shiprailgun_sounds = ShipRailgunSounds()
    shipmissile_sounds = ShipMissileSounds()
    shipexplode_sounds = ShipExplodeSounds()
    # Sets the volume to 0.1, (range is from 0.0 to 1.0).
    low_volume = 0.03
    mid_volume = 0.3
    high_volume = 0.7
    shipbullet_sounds.firing.set_volume(mid_volume)
    shiprailgun_sounds.start.set_volume(low_volume)
    shiprailgun_sounds.firing.set_volume(low_volume)
    shiprailgun_sounds.end.set_volume(low_volume)
    shipmissile_sounds.firing.set_volume(low_volume)
    shipexplode_sounds.start.set_volume(high_volume)

    # Actually, there is no need to import their classes into this file.
    parachutes = Group()
    u_rail = Group()
    u_secondary = Group()
    u_missile = Group()
    u_laser = Group()

    u_i_rail = Group()
    u_i_secondary = Group()
    u_i_missile = Group()
    u_i_laser = Group()

    # Actually, there is no need to import their classes into this file.
    explosions = Group()

    # Actually, there is no need to import their classes into this file.
    helis = Group()
    rockets = Group()
    ad_helis = Group()
    shipbullets = Group()
    shipmissiles = Group()
    helibullets = Group()

    # Create buttons to be pressed.
    play_button_mm = Button(screen, 'Play')
    stats_button_mm = Button(screen, 'Statistics')
    quit_button_mm = Button(screen, 'Quit Game')

    resume_button_esc = Button(screen, 'Resume')
    restart_button_esc = Button(screen, 'Restart Game')
    stats_button_esc = Button(screen, 'Statistics')
    exit_button_esc = Button(screen, 'Exit to Main Menu')
    #settings_button = Button(screen, 'Settings')

    # Reposition Main menu buttons based on the button above it.
    space_btw_buttons = 8
    stats_button_mm.rect.y += space_btw_buttons + play_button_mm.rect.height
    stats_button_mm.msg_image_rect.centery = stats_button_mm.rect.centery
    quit_button_mm.rect.y = space_btw_buttons + stats_button_mm.rect.y + stats_button_mm.rect.height
    quit_button_mm.msg_image_rect.centery = quit_button_mm.rect.centery

    # Reposition Esc menu buttons based on the button above it.
    restart_button_esc.rect.y += space_btw_buttons + resume_button_esc.rect.height
    restart_button_esc.msg_image_rect.centery = restart_button_esc.rect.centery
    stats_button_esc.rect.y = space_btw_buttons + restart_button_esc.rect.y + restart_button_esc.rect.height
    stats_button_esc.msg_image_rect.centery = stats_button_esc.rect.centery
    exit_button_esc.rect.y = space_btw_buttons + stats_button_esc.rect.y + stats_button_esc.rect.height
    exit_button_esc.msg_image_rect.centery = exit_button_esc.rect.centery

    #settings_button.rect.y = space_btw_buttons +
    #settings_button.msg_image_rect.centery = settings_button.rect.centery

    #print(pygame.display.Info())

    # Creating list for rocket and ad_helis.
    rockets_hits_list = []
    ad_helis_hits_list = []

    # Ensures that the events, internals and screen is always running.
    while True:
        ai_settings.time_game = float('{:.1f}'.format(get_process_time()))

        # In charge of checking all game events prior to screen updates.
        gf.check_events(ai_settings, screen, ship, shipbullets,
                        shipbullet_sounds, shiprailgun_sounds, shipmissiles,
                        shipmissile_sounds, shipexplode_sounds, parachutes,
                        u_rail, u_secondary, u_missile, u_laser, u_i_rail,
                        u_i_secondary, u_i_missile, u_i_laser, helis,
                        helibullets, rockets, rockets_hits_list, ad_helis,
                        ad_helis_hits_list, explosions, stats, play_button_mm,
                        stats_button_mm, quit_button_mm, resume_button_esc,
                        restart_button_esc, stats_button_esc, exit_button_esc,
                        sb, gameclock)

        # Updates all game internal functions prior to screen updates and only when game is active.
        if stats.game_active:
            #ai_settings.time_game_play = float('{:.1f}'.format(get_process_time()))
            # When the game is active, calculate the play time.
            ai_settings.time_game_total_play = ai_settings.time_game - ai_settings.time_game_start - ai_settings.time_game_total_pause

            gf.update_internals(
                ai_settings, screen, ship, shipbullets, shipbullet_sounds,
                shiprailgun_sounds, shipmissiles, shipmissile_sounds,
                shipexplode_sounds, parachutes, u_rail, u_secondary, u_missile,
                u_laser, u_i_rail, u_i_secondary, u_i_missile, u_i_laser,
                helis, helibullets, rockets, rockets_hits_list, ad_helis,
                ad_helis_hits_list, explosions, stats, sb, gameclock)
        elif stats.game_pause:
            # When the game is paused, only update/calculate the pause time.
            ai_settings.time_game_single_pause = ai_settings.time_game - ai_settings.time_game_pause_start

        # Updates the screen with all the objects and projectiles.
        gf.update_screen(ai_settings, screen, ship, shipbullets, shipmissiles,
                         parachutes, u_rail, u_secondary, u_missile, u_laser,
                         u_i_rail, u_i_secondary, u_i_missile, u_i_laser,
                         helis, helibullets, rockets, ad_helis, explosions,
                         stats, play_button_mm, stats_button_mm,
                         quit_button_mm, resume_button_esc, restart_button_esc,
                         stats_button_esc, exit_button_esc, sb, gameclock, bg)
Пример #18
0
 def __init__(self, window):
     self.Background = Background(window)
     self.ToolBox = ToolBox(*window.size)
def main():
    '''main program'''
    pygame.init()

    #setting up font

    #set height and width of the screen'''
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('Side-Scrollin Platformer')
    BackGround = Background('background_test.jpeg', [0, 0])
    #create the player'''
    player = Player()
    #crate levels'''
    level_list = []
    level_list.append(Level_01(player))
    level_list.append(Level_02(player))
    #set current level'''
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    #loop until the user clicks close button'''
    done = False
    #used to manage how fast the screen updates'''
    clock = pygame.time.Clock()

    projectile_list = pygame.sprite.Group()
    bullet_list = pygame.sprite.Group()

    #MAIN GAME LOOP'''
    while not done:
        screen.fill(WHITE)
        screen.blit(BackGround.image, BackGround.rect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    player.go_left()
                if event.key == pygame.K_d:
                    player.go_right()
                if event.key == pygame.K_w:
                    player.jump()
                    #player.subtract_health(3)
                    #message_display(player.health)
                    #text(player.health)
                    #print (player.health)

                if event.key == pygame.K_SPACE:
                    bullet = Projectile(player.rect.x, player.rect.y, 12, 0)
                    active_sprite_list.add(bullet)
                    bullet_list.add(bullet)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_d and player.change_x > 0:
                    player.stop()

        #dropping projectiles

        odds_of_drop = random.randint(1, 100)
        if odds_of_drop < 10:
            projectile = Projectile(random.randrange(SCREEN_WIDTH),
                                    random.randrange(1, 5), 0,
                                    random.randrange(5, 8))
            active_sprite_list.add(projectile)
            projectile_list.add(projectile)

        hits = pygame.sprite.spritecollide(player, projectile_list, True)
        if hits:
            player.subtract_health(1)
            #projectile_list.remove(projectile)
            print("hit")
            print(player.health)
            #projectile.kill()

    #update player'''op
        active_sprite_list.update()
        #update items in the level'''
        current_level.update()
        #if player gets near the right side, shift the world left (-x)'''
        if player.rect.right >= 500:
            diff = player.rect.right - 500
            player.rect.right = 500
            current_level.shift_world(-diff)
    #if player gets near the left side, shift the world right(+x)'''
        if player.rect.left <= 120:
            diff = 120 - player.rect.left
            player.rect.left = 120
            current_level.shift_world(diff)
    #if the player gets to the end of the level, go to next level'''
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

    #all code to draw should go below this comment'''
        current_level.draw(screen)
        active_sprite_list.draw(screen)
        #all code to draw should go above this comment'''

        #limt to 6o fps'''
        clock.tick(60)

        #go ahead and update the screen with what weve drawn'''
        pygame.display.flip()


#be IDLE friendly. if you foget this line program will hang on exit'''
    pygame.quit()
Пример #20
0
def run_game():

    # Inicializa o pygame, as configuraçoes e o objeto screen.
    pygame.init()  # Inicia as configuraçôes de segundo plano.
    ai_settings = Settings()  # Cria uma instância.
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)
    )  # Superfície onde definimos sua dimensão. É uma janela de exibições para desenhar todos os elementos gráficos do jogo.

    pygame.display.set_caption("Alien Invasion - By Portela")

    # Cria o botão Play.
    play_button = Button(ai_settings, screen, "Play")  # cria uma instância.

    # Cria instância para armazenar estatísticas do jogo e cria painel de pontuação.
    stats = GameStats(ai_settings)  # cria uma instância.

    # Obtem a pontuação máxima.
    stats.high_score = gf.updateFile(stats)

    sb = Scoreboard(ai_settings, screen, stats)  # cria uma instância.

    # Cria uma espaçonave.
    ship = Ship(ai_settings, screen)

    # Cria um grupo no qual serão armazenados os projéteis.
    bullets = Group()  # cria uma instância.

    # Cria um grupo de alienígenas.
    aliens = Group()  # cria uma instância.

    # Cria o Background.
    background = Background('images/earth.bmp', [0, 0])

    # Cria a frota de alienígenas.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Inicia o laço principal do jogo.
    while True:

        # Observa eventos de teclado e de mouse.
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ''' O jogo deverá ficar congelado quando todas as três espaçonaves forem usadas. '''

            # Atualiza a posição da espaçonave de acordo com a flag de movimento.
            ship.update()
            ''' Atualiza as posiçôes dos projéteis de acordo com a flag de movimento da espaçonave
                e livra-se dos projéteis que desapareceram. '''
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)

            # Monitora o número de espaçonaves que restam ao jogador.
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

        # Pega as posiçôes atualizadas e redesenha uma nova tela a cada passagem pelo laço.
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                         background, bullets, play_button)
Пример #21
0
    def load(self):
        self.background_group = pygame.sprite.Group()
        self.game_group = pygame.sprite.LayeredDirty()
        self.ui_group = pygame.sprite.LayeredDirty()
        self.tutorial_group = pygame.sprite.Group()

        self.background_group.add(Background(V2(0, 0)))

        # Me
        homeworld = Planet(self, V2(60, game.RES[1] - 40), 7,
                           Resources(100, 0, 0))
        homeworld.change_owner(self.my_civ)
        homeworld.population = 4
        homeworld.ships['fighter'] = 2
        homeworld.add_building("mining_rate")
        self.game_group.add(homeworld)

        # Alien
        p = Planet(self, V2(420, 60), 5, Resources(70, 20, 10))
        p.change_owner(self.enemy.civ)
        p.population = 5
        p.ships['alien-fighter'] = 2
        self.game_group.add(p)
        num_planets = 2

        # TODO: Planet resources more constrained
        while num_planets < 15:
            pos = V2(random.randint(30, game.RES[0] - 30),
                     random.randint(30, game.RES[1] - 30))

            near_button = pygame.Rect(game.RES[0] / 2 - 100, game.RES[1] - 60,
                                      200, 60)
            if near_button.collidepoint(*pos.tuple()):
                continue

            near_meters = pygame.Rect(0, 0, 250, 60)
            if near_meters.collidepoint(*pos.tuple()):
                continue

            dist = 999999
            for planet in self.get_planets():
                delta = (planet.pos - pos).sqr_magnitude()
                if delta < dist:
                    dist = delta
            if dist > 70**2:
                if pos.x / 2 + (game.RES[1] - pos.y) < game.RES[1] - 100:
                    size = random.randint(4, 7)
                    if random.random() > 0.5:
                        pr = Resources(100, 0, 0)
                    else:
                        size -= 1
                        iron = random.randint(7, 10)
                        pr = Resources(iron * 10, (10 - iron) * 10, 0)
                else:
                    size = random.randint(3, 7)
                    resources = {'a': 0, 'b': 0, 'c': 0}
                    # One resource
                    ra = random.random()
                    if ra > 0.75:
                        resources['a'] = 10
                    # Two resource
                    elif ra > 0.33:
                        resources['a'] = random.randint(5, 10)
                        resources['b'] = 10 - resources['a']
                    # Three
                    else:
                        resources['a'] = random.randint(1, 7)
                        resources['b'] = random.randint(1, 10 - resources['a'])
                        resources['c'] = 10 - resources['a'] - resources['b']
                    rb = random.random()
                    if rb > 0.6:
                        pr = Resources(resources['a'] * 10,
                                       resources['b'] * 10,
                                       resources['c'] * 10)
                        size += 1
                    elif rb > 0.25:
                        pr = Resources(resources['b'] * 10,
                                       resources['a'] * 10,
                                       resources['c'] * 10)
                    else:
                        pr = Resources(resources['c'] * 10,
                                       resources['b'] * 10,
                                       resources['a'] * 10)
                        size -= 1
                self.game_group.add(Planet(self, pos, size, pr))
                num_planets += 1

        self.meters = {}
        self.upgrade_texts = {}
        for i, r in enumerate(self.my_civ.resources.data.keys()):
            self.meters[r] = Meter(V2(15,
                                      3 + i * 14), 120, 9, RESOURCE_COLORS[r],
                                   self.my_civ.upgrade_limits.data[r])
            self.meters[r].stay = True
            self.ui_group.add(
                SimpleSprite(V2(2, 2 + i * 14), "assets/i-%s.png" % r))
            self.ui_group.add(self.meters[r])
            self.upgrade_texts[r] = Text("",
                                         "small",
                                         V2(140, 4 + i * 14),
                                         multiline_width=200)
            self.ui_group.add(self.upgrade_texts[r])

        self.my_civ.resources.on_change(self.on_civ_resource_change)

        self.upgrade_button = Button(V2(game.RES[0] / 2, game.RES[1] - 4),
                                     "UPGRADE", "big", self.on_click_upgrade)
        self.upgrade_button.offset = (0.5, 1)
        self.upgrade_button._recalc_rect()
        self.upgrade_button.visible = 0
        self.ui_group.add(self.upgrade_button)

        self.help_button = Button(V2(2, 48), "Help", "small",
                                  self.on_click_help)
        self.ui_group.add(self.help_button)

        self.score_label = Text("- Score -", "small", V2(game.RES[0] - 2, 2),
                                PICO_BLUE)
        self.score_label.offset = (1, 0)
        self.score_label._recalc_rect()
        self.ui_group.add(self.score_label)

        self.score_text = Text("0", "small", V2(game.RES[0] - 2, 12),
                               PICO_BLUE)
        self.score_text.offset = (1, 0)
        self.score_text._recalc_rect()
        self.ui_group.add(self.score_text)

        self.my_civ.resources.set_resource("iron", 30)

        if self.options == "iron":
            self.my_civ.resources.set_resource("iron", 150)

        if self.options == "ice":
            self.my_civ.resources.set_resource("ice", 150)

        if self.options == "gas":
            self.my_civ.resources.set_resource("gas", 150)

        if self.options == "surround":
            for planet in self.get_civ_planets(None):
                planet.change_owner(self.enemy.civ)
                planet.add_ship("alien-fighter")
                planet.add_ship("alien-fighter")
                #self.my_civ.resources.set_resource("iron", 50)
                #self.my_civ.resources.set_resource("ice", 50)
                self.my_civ.resources.set_resource("gas", 50)

        if self.options == "fighters":
            for i in range(20):
                homeworld.add_ship("fighter")

        if self.options == "battleship":
            from ships.alienbattleship import AlienBattleship
            bs = AlienBattleship(self, V2(150, 250), self.enemy.civ)
            bs.target = homeworld
            self.game_group.add(bs)

        if self.options == "fast":
            self.game_speed = 10

        if self.options == "score":
            homeworld.change_owner(self.enemy.civ)
Пример #22
0
    def __init__(self, settings, screen, clock):
        """Initialise the menu's settings, pages, layout, and UI elements."""

        # UIManager keeps track of pygame_gui elements
        self.ui_manager = gui.UIManager(settings.screen_size)
        self.screen = screen
        self.clock = clock

        self.background = Background(settings, screen)
        self.fonts = {
            "large": pygame.freetype.SysFont(name=None, size=32),
            "small": pygame.freetype.SysFont(name=None, size=16),
        }
        title_image = pygame.image.load(settings.title_image_path)

        # menu layout settings
        self.button_width = 0.3 * screen.get_width()
        self.button_height = 40
        self.button_vspace = self.button_height * 1.2
        self.button_size = (self.button_width, self.button_height)
        self.corner_button_size = (0.5 * self.button_width, self.button_height)

        # initialise rects for positioning and sizing elements
        self.containers = self.init_container_rects()
        self.button_rects = self.init_button_rects()

        # other pages are components of menu, they share much of menu's state
        self.tutorial = Tutorial(settings, screen, clock, self.containers)
        self.settings_menu = SettingsMenu(settings, screen, clock,
                                          self.containers, self.fonts)

        # create menu elements, these will be drawn every frame
        self.title = gui.elements.UIImage(
            relative_rect=self.containers['title'],
            image_surface=title_image,
            manager=self.ui_manager)

        self.play_sandbox_button = gui.elements.UIButton(
            relative_rect=self.button_rects['play_sandbox'],
            text='Play game in sandbox mode',
            manager=self.ui_manager)

        self.play_ai_easy_button = gui.elements.UIButton(
            relative_rect=self.button_rects['play_ai_easy'],
            text='Play game against easy AI',
            manager=self.ui_manager)

        self.play_ai_hard_button = gui.elements.UIButton(
            relative_rect=self.button_rects['play_ai_hard'],
            text='Play game against hard AI',
            manager=self.ui_manager)

        self.tutorial_button = gui.elements.UIButton(
            relative_rect=self.button_rects['tutorial'],
            text='How to play',
            manager=self.ui_manager)

        self.settings_button = gui.elements.UIButton(
            relative_rect=self.button_rects['settings'],
            text='Settings',
            manager=self.ui_manager)

        self.quit_button = gui.elements.UIButton(
            relative_rect=self.button_rects['quit'],
            text='Quit',
            manager=self.ui_manager)
Пример #23
0
import sys

import pygame

import math

#this is a comment to test git

from bullet import Bullet
from turret import Turret
from enemy import Enemy
from background import Background
background = Background('images/background.png',(0,0))


black = (0,0,0)

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()
def message_display(ai_settings, text, screen):
    largeText = pygame.font.Font('freesansbold.ttf', 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = (ai_settings.screen_width/2, ai_settings.screen_height/2)
    screen.blit(TextSurf, TextRect)
def update_mouse():
    p = pygame.mouse.get_pos()
    return str(p)

def check_keydown_events(event, ai_settings, screen, ship,  bullets):
    if event.key == pygame.K_RIGHT:
Пример #24
0
def run_game():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("images/bg2.ogg")
    pygame.mixer.music.set_volume(0.2)
    pygame.mixer.music.play(-1, 0)

    icon = pygame.image.load("images/app.ico")
    pygame.display.set_icon(icon)
    pygame.display.set_caption("Aircraft war")
    screen_size = (512, 768)
    screen = pygame.display.set_mode(screen_size)

    setting = Settings()
    score = Score(setting, screen)
    background = Background(screen, screen_size, setting)
    play_button = Button(screen, 'Play', 48)
    ship = Ship(screen)
    ship_bullets = pygame.sprite.Group()
    enemys = pygame.sprite.Group()
    enemys_bullets = pygame.sprite.Group()
    bombs = pygame.sprite.Group()

    while True:
        for event in pygame.event.get():      # 这句话只能有一个
            if event.type == pygame.QUIT:
                sys.exit()

            if not setting.game_active:
                # 按Play键重置并开始游戏
                if event.type == pygame.MOUSEBUTTONDOWN:
                    click = pygame.mouse.get_pos()
                    if play_button.rect.collidepoint(click):
                        setting.reset()
                        score.render_score()
                        background.refresh(setting)
                        enemys.empty()
                        enemys_bullets.empty()
                        ship.put()
                        setting.game_active = True

            if setting.game_active:
                # 更新我方飞机位置
                update_ship(screen, ship, ship_bullets)
                # 鼠标拖动飞机
                if event.type == pygame.MOUSEMOTION:
                    buttons = pygame.mouse.get_pressed()
                    if buttons[0]:
                        position = pygame.mouse.get_pos()
                        ship.rect.centerx = position[0]
                        ship.rect.centery = position[1]
                # 每隔2.5秒飞下来4架敌机并发射子弹
                if event.type == create_enemy:
                    enemy = [Enemy(screen, setting) for _ in range(4)]
                    enemys.add(enemy)
                    for i in enemys.sprites():
                        enemy_bullet = Bullet(screen, i, is_enemy=True)
                        enemys_bullets.add(enemy_bullet)
                # 每隔60秒更新关卡
                if event.type == refresh_level:
                    setting.refresh_level()
                    background.refresh(setting)

        detect_collision(screen, ship, ship_bullets, enemys, enemys_bullets, bombs, setting, score)
        update_screen(setting, background, ship, ship_bullets, enemys, enemys_bullets, bombs, play_button, score)
Пример #25
0
from settings import Settings
from background import Background
import game_functions as gf
from pygame.sprite import Group, groupcollide
from zombie import Zombie
from square import Square
from plant_icon import Plant_Icon
import time

# initiate pygame, instantiate classes (passing arguments if needed), create needed variables
pygame.init()
game_settings = Settings(
)  # instantiate Settings() from settings.py to use the class
screen = pygame.display.set_mode(game_settings.screen_size)
pygame.display.set_caption("DC PvZ clone")
background = Background(game_settings)
peashooter_icon = Plant_Icon(game_settings, 'peashooter-icon.png', 1)
gatling_icon = Plant_Icon(game_settings, 'gatling-icon.png', 2)
sunflower_icon = Plant_Icon(game_settings, 'sunflower-icon.png', 3)
icons = [peashooter_icon, gatling_icon, sunflower_icon]

zombies = Group()  # Group() comes from pygame.sprite
plants = Group()
squares = Group()
bullets = Group()

# print game_settings.squares["rows"][1]

for i in range(0, 5):
    for j in range(0, 9):
        squares.add(Square(screen, game_settings, i, j))
Пример #26
0
def enter():
    delay(3)
    global background

    background = Background()
Пример #27
0
ADD_PIPE = gf.create_user_events(settings)

# Setup a clock
clock = pygame.time.Clock()

# Set display's parameters
pygame.display.set_caption(settings.screen_caption)
screen = pygame.display.set_mode(
    (settings.screen_width, settings.screen_height))

# Check game stats
stats = GameStats(screen, settings)

# Create instances for bird, background and pipes
bird = Bird(screen, settings, stats)
background = Background(screen, settings)
pipes_bottom = Group()
pipes_top = Group()

# draw the screen for the first time
gf.update_screen(screen, background, bird, pipes_bottom, pipes_top, stats)

# enter game loop
while True:
    # check external and interval
    gf.check_events(settings, screen, bird, ADD_PIPE, pipes_bottom, pipes_top,
                    stats)

    # if game is not active freeze the screen and wait for event
    if stats.game_active:
        gf.update_screen(screen, background, bird, pipes_bottom, pipes_top,
Пример #28
0
    def rodar(self):
        self.rodando = True
        fps = 12

        self.Pfundo = Background(self.amb, self.screen, self)
        self.music = Music(self.amb)
        self.menu = Menu(self.amb, self.screen, 150, (290,165), self) 
        self.telaselect = Telaselecao(self.amb, self.screen)
        
        self.barra_vida = self.amb.image.load("../img/Lifebar/lifebar.png").convert_alpha()

        self.carregar_animacao_inicial()

        while self.rodando:
            self.screen.fill((0, 0, 0))

            self.Pfundo.desenhar()
            
            self.music.verificar_ativacao()

            if self.menu_ativo:
                self.menu.desenhar()
            
            elif self.telaselecao_ativo:
                self.telaselect.desenhar()
                self.count = 0
            
            else:
                self.iniciar_jogo()

            for event in self.amb.event.get():                
                
                self.key = self.amb.key.get_pressed()
                
                if event.type == self.amb.QUIT:
                    self.rodando = False
                
                if event.type == self.amb.KEYDOWN:
                    if self.menu_ativo:
                        if self.menu.instrucoes:
                            self.menu.eventos_instrucoes(self.key)
                        
                        else:
                            self.menu.tratar_eventos(self.key)
                    
                    elif self.telaselecao_ativo:
                        self.telaselect.tratar_eventos(self.key, self)
                    
                    else:
                        self.player1.tratar_eventos(self.key)
                        self.player2.tratar_eventos(self.key)

                        if self.jogo_acabou:
                            if self.key[self.amb.K_F5]:
                                self.menu_ativo = True
                                self.count = 0
                                self.lista_tempo_1 = []

                            elif self.key[self.amb.K_RETURN]:
                                self.criar_lutadores()
                                self.count = 0
                                self.lista_tempo_1 = []

                            self.jogo_acabou = False
                    
                    if self.key[self.amb.K_EQUALS]:
                        if fps <= 20:
                            fps += 1

                    if self.key[self.amb.K_MINUS]:
                        if fps > 1:
                            fps -= 1

                if event.type == self.amb.KEYUP:
                    if self.menu_ativo is False and self.telaselecao_ativo is False:
                        
                        if self.player1.vivo:
                            if event.key == self.player1.frente or event.key == self.player1.tras:
                                self.player1.trocar_estado("parado")

                        if self.player2.vivo:
                            if event.key == self.player2.frente or event.key == self.player2.tras:
                                self.player2.trocar_estado("parado")
            
            self.amb.display.flip()
            
            self.clock.tick(fps)

        self.amb.quit()
Пример #29
0
 def create_backgound(self):
     from background import Background
     self.__background = background = Background(self.__canvas)
     self.__timer_list.append(background)
    elif mission == 'TESS':
        dt = 30.0*60.0
        obs_time = raw_input("How long is observing time (long/short)?\n")
        if obs_time == 'long':
            T = 356.2 * 86400.0
        elif obs_time == 'short':
            T = 164.4 * 86400.0

    nyq = 1.0 / (2.0 * dt) * 1e6
    freq = np.arange(0, nyq, (1.0 / T)*1e6)


    print("REMEMBER TO INCLUDE 0.85 FACTOR IN ALL AMPLITUDES AND CHANGE IN MODE VISIBILITIES FOR TESS MISSION!!!!")
    print("PROBLEM WITH CALCULATING l=1 HEIGHTS, TALK TO BILL!!!")
    # Set up class for scaling relations
    backg = Background(freq, nyq, dnu, numax, dt, kmag, N=1, \
                       mission=mission)
    model = backg()
    try:
        freq_0 = np.loadtxt('test_radial.txt')
    except:
        freq_0 = []
    modes = RadialModes(freq, model, Teff, kmag, dnu, numax, dpi, epsg, q, gsplit, R, \
                  inc, dt, T, N=1, mission='Kepler')
    modes.create_radial_modes(freq_0)
    l2 = QuadrupoleModes(modes,[])
    l2.create_quadrupole_modes()

    # Create power spectrum -> multiply by chi2 2dof noise
    power = model * -1.0 * np.log(np.random.uniform(0,1,len(freq)))

    pl.plot(freq, power, 'k')