Exemplo n.º 1
0
ai_settings = Settings()
ai_settings.initDynamicSettings()
pygame.display.set_caption('Side Scroller')
screen = pygame.display.set_mode((ai_settings.W, ai_settings.H))
sb = Scoreboard(ai_settings, screen)

clock = pygame.time.Clock()

runner = Runner(400, 300, 75, 75)
# for increasing speed, setting up obstacles, setting up coins respectively
pygame.time.set_timer(USEREVENT + 1, 500)
pygame.time.set_timer(USEREVENT + 2, random.randrange(3000, 5000))
pygame.time.set_timer(USEREVENT + 3, 3000)
run = True
objects = []
coins = Group()

while run:
    gf.checkEvents(runner, ai_settings)
    if ai_settings.gameActive:
        emptyObj = gf.updateScreen(ai_settings, screen, runner, objects, coins,
                                   sb)
        # for emptying the coins and obstacles if runner hits obstacle
        if emptyObj == True:
            objects = []
            for x in coins:
                coins.remove(x)

        # for creating obstacles, coins, and increases speed
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
Exemplo n.º 2
0
B_PENGUIN_IMGS = []
for img in F_PENGUIN_IMGS:
    B_PENGUIN_IMGS.append(pygame.transform.flip(img, True, False))

STAT_FONT = pygame.font.SysFont('comicsans', 35)

HEIGHT = BG_IMGS[0].get_height()
WIDTH = BG_IMGS[0].get_width()

done = False
bg = Background(settings, BG_IMGS, HEALTH_IMG, PROJECTILE_IMG)
player = Player(settings, 100, 620, F_PENGUIN_IMGS, B_PENGUIN_IMGS)
enemies = [Enemy(settings, 1200, random.randint(530, 630), B_PENGUIN_IMGS)]

loot_list = []
enemy_bullets = Group()
player_bullets = Group()
clock = pygame.time.Clock()

while not done:
    gf.check_events(settings, player, player_bullets, F_PROJECTILE_IMG,
                    B_PROJECTILE_IMG)
    player.update()
    gf.update_enemy_bullets(enemy_bullets, player)
    gf.update_player_bullets(settings, player_bullets, enemies, loot_list,
                             LOOT_IMGS)
    gf.update_enemies(settings, enemies, B_PENGUIN_IMGS)
    gf.take_shot(settings, enemy_bullets, enemies, player, F_PROJECTILE_IMG,
                 B_PROJECTILE_IMG)
    gf.update_loot(settings, loot_list, player)
    bg.draw(settings, screen, enemies, player_bullets, enemy_bullets,
Exemplo n.º 3
0
    def __init__(self, screen):
        """ Initialize the player and set her initial position."""
        # Load the screen.
        self.screen = screen

        # Load the player's image and Rect object.
        self.image = pygame.image.load(PLAYER_IMAGE_PATH)
        self.image = self.image.convert_alpha()
        self.image.fill((255, 255, 255, PLAYER_IMAGE_ALPHA), None,
                        pygame.BLEND_RGBA_MULT)
        self.rect = self.image.get_rect()
        self.rect_origin = self.rect.copy()
        self.screen_rect = self.screen.get_rect()

        # Start the player at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # Store the float value of player's center.
        self.centerx = float(self.rect.centerx)
        self.centery = float(self.rect.centery)

        # Load the collision box.
        self.collision_box = CircleShape(
            alpha=255,
            color_edge=PLAYER_COLLISION_BOX_COLOR_EDGE,
            color_inside=PLAYER_COLLISION_BOX_COLOR_INSIDE,
            radius=PLAYER_COLLISION_BOX_RADIUS,
            width=PLAYER_COLLISION_BOX_WIDTH,
            screen=self.screen)

        # Set the player's moving flags.
        self.moving_up = False
        self.moving_down = False
        self.moving_left = False
        self.moving_right = False

        # Set the player's speed.
        self.speed = PLAYER_SPEED

        # Set the player's power.
        self.power = 125

        # Set the kwargs of the bullets.
        bullet_image = pygame.image.load(
            PLAYER_BULLET_IMAGE_PATH).convert_alpha()
        bullet_image.fill((255, 255, 255, PLAYER_BULLET_IMAGE_ALPHA), None,
                          pygame.BLEND_RGBA_MULT)
        bullet_shape_kwargs = {
            'shape_type': 'ImageShape',
            'image': bullet_image,
            'screen': self.screen
        }
        self.bullet_kwargs = {
            **bullet_shape_kwargs,
            **PLAYER_BULLET_MOTION_KWARGS
        }

        # Create the bullet group of the player.
        self.bullets = Group()

        # Set the player's shooting flag
        self.shooting = False
Exemplo n.º 4
0
def gameInit():

    version = '0.8e'
    versionString = 'zoot v' + version

    print ' ' + versionString

    display.clearColor = (32, ) * 3
    display.reset(width, height)

    init()

    set_caption(versionString)

    menuSetup = ('&Resume', 'play', 'K_ESCAPE'), \
              None, \
              ('&New game', 'new game'), \
              ('&Save', 'save'), \
              ('&Load', 'load'), \
              ('&Quit', 'quit')

    game.menu = menuGroup(menuSetup)
    game.menu.rect.centerx = width / 2
    game.menu.rect.centery = height / 2
    game.menu.subscript(versionString)

    game.grid = gridGroup(gridWidth, (-4, gridHeight), blockBase)
    game.nextGrid = gridGroup(4, 4, blockBase,
                              game.grid.pxWide + 2 * blockBase,
                              game.grid.pxTall / 3 - 2 * blockBase)
    game.holdGrid = gridGroup(4, 4, blockBase,
                              game.grid.pxWide + 2 * blockBase,
                              game.grid.pxTall / 3 * 2)

    # string offset [fontsize] [color]
    levelLabel = labelSprite('level 1 - 0', ((size[0] - 80), size[1] - 20))
    nextLabel = labelSprite(
        'Next up:',
        (game.nextGrid.borderRect.left + 4, game.nextGrid.borderRect.top - 20))
    holdLabel = labelSprite(
        'Hold:',
        (game.holdGrid.borderRect.left + 4, game.holdGrid.borderRect.top - 20))
    game.ui = Group(levelLabel, nextLabel, holdLabel)

    game.msg.handler('levelLabel')(levelLabel.text)

    from os.path import isfile

    game.stdCursor = get_cursor()

    game.saveFile = osJoin(abspath(game.dir), 'zoot.save')

    game.saveRegister = []
    for name, obj in game.__dict__.iteritems():
        if hasattr(obj, 'save'):
            if callable(obj.save) and not isinstance(obj, type):
                game.saveRegister.append((name, obj))

    game.sm.autoSwitch = {'new game': 'play', 'load': 'play', 'save': 'play'}

    if isfile(game.saveFile):
        game.sm.autoSwitch['init'] = 'load'
    else:
        game.sm.autoSwitch['init'] = 'new game'
Exemplo n.º 5
0
def check_matches(settings, screen, blocks, board, score):
    to_remove = [[]]
    # Checks matches for each block in the array of blocks.
    for block in blocks:
        x = block.board_x
        y = block.board_y

        # Checks horizontally.
        h_remove = [block]
        if x >= 1 and isinstance(board[y][x - 1], Block):
            if board[y][x - 1].color == block.color:
                h_remove.append(board[y][x - 1])
                if x >= 2 and isinstance(board[y][x - 2], Block):
                    if board[y][x - 2].color == block.color:
                        h_remove.append(board[y][x - 2])
        if x <= 4 and isinstance(board[y][x + 1], Block):
            if board[y][x + 1].color == block.color:
                h_remove.append(board[y][x + 1])
                if x <= 3 and isinstance(board[y][x + 2], Block):
                    if board[y][x + 2].color == block.color:
                        h_remove.append(board[y][x + 2])
        if len(h_remove) >= 3:
            to_remove.append(h_remove)

        # Checks vertically.
        v_remove = [block]
        if y >= 1 and isinstance(board[y - 1][x], Block):
            if board[y - 1][x].color == block.color:
                v_remove.append(board[y - 1][x])
                if y >= 2 and isinstance(board[y - 2][x], Block):
                    if board[y - 2][x].color == block.color:
                        v_remove.append(board[y - 2][x])
        if y <= 10 and isinstance(board[y + 1][x], Block):
            if board[y + 1][x].color == block.color:
                v_remove.append(board[y + 1][x])
                if y <= 9 and isinstance(board[y + 2][x], Block):
                    if board[y + 2][x].color == block.color:
                        v_remove.append(board[y + 2][x])
        if len(v_remove) >= 3:
            to_remove.append(v_remove)

        # Checks angle top left to bottom right.
        ua_remove = [block]
        if x >= 1 and y >= 1 and isinstance(board[y - 1][x - 1], Block):
            if board[y - 1][x - 1].color == block.color:
                ua_remove.append(board[y - 1][x - 1])
                if x >= 2 and y >= 2 and isinstance(board[y - 2][x - 2],
                                                    Block):
                    if board[y - 2][x - 2].color == block.color:
                        ua_remove.append(board[y - 2][x - 2])
        if x <= 4 and y <= 10 and isinstance(board[y + 1][x + 1], Block):
            if board[y + 1][x + 1].color == block.color:
                ua_remove.append(board[y + 1][x + 1])
                if x <= 3 and y <= 9 and isinstance(board[y + 2][x + 2],
                                                    Block):
                    if board[y + 2][x + 2].color == block.color:
                        ua_remove.append(board[y + 2][x + 2])
        if len(ua_remove) >= 3:
            to_remove.append(ua_remove)

        # Checks angle bottom left to top right.
        da_remove = [block]
        if x >= 1 and y <= 10 and isinstance(board[y + 1][x - 1], Block):
            if board[y + 1][x - 1].color == block.color:
                da_remove.append(board[y + 1][x - 1])
                if x >= 2 and y <= 9 and isinstance(board[y + 2][x - 2],
                                                    Block):
                    if board[y + 2][x - 2].color == block.color:
                        da_remove.append(board[y + 2][x - 2])
        if x <= 4 and y >= 1 and isinstance(board[y - 1][x + 1], Block):
            if board[y - 1][x + 1].color == block.color:
                da_remove.append(board[y - 1][x + 1])
                if x <= 3 and y >= 2 and isinstance(board[y - 2][x + 2],
                                                    Block):
                    if board[y - 2][x + 2].color == block.color:
                        da_remove.append(board[y - 2][x + 2])
        if len(da_remove) >= 3:
            to_remove.append(da_remove)

    # Stores columns that need to be moved down after removal.
    cols = set()

    # Removes appropriate blocks from the board.
    num_remove = 0
    for remove in to_remove:
        for block in remove:
            num_remove += 1
            board[block.board_y][block.board_x] = 0
            cols.add(block.board_x)
    column = Group()
    update_screen(settings, screen, column, board, score)

    # Adds to score based on the number of blocks removed.
    if num_remove >= 5:
        score[0] += num_remove * 1500
    elif num_remove == 4:
        score[0] += num_remove * 1000
    elif num_remove == 3:
        score[0] += num_remove * 500

    # Pauses if anything was removed so that the user can better understand what's happening.
    if len(remove) != 0:
        pygame.time.wait(1000)

    # Returns the cols so that they can be checked in move_down.
    return cols
Exemplo n.º 6
0
from game_objects import Player, Background
import game_fuction as gf
from stats import GameStats
from button import Button

pygame.init()
pygame.display.set_caption('Catch This')
ct_settings = Settings()
screen = pygame.display.set_mode((ct_settings.width, ct_settings.height))
clock = pygame.time.Clock()
stats = GameStats(ct_settings)
sb = Scoreboard(ct_settings, stats, screen)
play_button = Button(screen, 'Play')

#Groups
friends = Group()
enemies = Group()
bonus = Group()

#Game objects
player = Player(ct_settings, screen)
background = Background(ct_settings, screen)

while True:
    gf.check_events(bonus, ct_settings, enemies, friends, play_button, player, sb, stats)
    if stats.game_active:
        player.update()
        gf.update_enemies(bonus, clock, ct_settings, enemies, friends, player, sb, stats)
        gf.update_friends(ct_settings, clock, sb, stats, player, friends)
        gf.update_bonus(bonus, clock, ct_settings, player, sb, stats)
    gf.update_screen(background, bonus, ct_settings, sb, screen, stats, play_button, player, friends, enemies)
Exemplo n.º 7
0
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from alien import Alien
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
from timeit import default_timer as timer

from pygame.sprite import Sprite
from pygame import Surface
alien1 = 0
bunker = 0
bulletCollidedWithBunker = False
bunkerGroup = Group()
bunkerRect = 0
rowForBunkerPixel = 50
columnForBunkerPixel = 270





class Bunker1(Surface):
    def __init__(self,image):

        self.image = image
        self.rect = image.get_rect(center=(50,300))

        self.rect.x = 50
Exemplo n.º 8
0
import pygame
from Archer import Archer
from Monsters import *
from SETTINGS import *
from Arrow import Arrow
from pygame.sprite import Group, groupcollide
from Wall import Wall
from Button import Start_Button

player = Archer()
monsters = pygame.sprite.Group()
wolf = Wolf()
monsters.add(wolf)
arrows =Group()
wall = Wall()
walls = Group()
walls.add(wall)
pygame.init()
pygame.mixer.init()
start_button = Start_Button(pygame_screen)
tick = 0 
gameOn = True
game_start = False
bg_music_sound = pygame.mixer.Sound('music.wav')
shoot_sound = pygame.mixer.Sound('shoot.wav')
pygame.display.set_caption(TITLE)

while gameOn:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
Exemplo n.º 9
0
from pygame.constants import *
from pygame import display
from pygame.sprite import Group

from core import color
from core import config

from core.config import screen, _limit_frame
from core.gamestate import GameState
from game.hudobject import HudObject
from game.mainmenu import MainMenu

### Groups #####################################################################
DIAMOND = Group()
################################################################################

### Constants ##################################################################
LOGO = config.load_image('logo.png')
BOOT = config.load_sound('boot.ogg')
################################################################################

### Preparation ################################################################

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


class SplashScreen(GameState):
    def __init__(self):
        self.alpha_percent = 0.0
        self.group_list = (DIAMOND, )
        self.logo = HudObject(LOGO, [0, 0])
Exemplo n.º 10
0
    def __init__(self):
        super().__init__()

        self.image = load('images/inimigo_1.png')
        self.rect = self.image.get_rect(center=(1280, randint(20, 580)))

    def update(self):
        global perdeu
        self.rect.x -= 0.1

        if self.rect.x == 0:
            self.kill()
            perdeu = True


grupo_inimigos = Group()
grupo_torradas = Group()
dunofausto = Dunofausto(grupo_torradas)
grupo_duno = GroupSingle(dunofausto)

grupo_inimigos.add(Virus())

clock = Clock()
mortes = 0
round = 0
perdeu = False

while True:
    # Loop de eventos

    clock.tick(120)  # FPS
Exemplo n.º 11
0
from enemy import Enemy

pygame.init()

screenSize = (600, 460)

pygame_screen = pygame.display.set_mode(screenSize)

pygame.display.set_caption('Super Mario Brothers')

backgroundImage = pygame.image.load('marioworld.png')
monster_image = pygame.image.load('goblin.png')  # Added by Brian

#Added by Brian
monster = Enemy()
monsters = Group()
monsters.add(monster)

clock = pygame.time.Clock()
mario = Mario()
marios = Group()
marios.add(mario)
gameOn = True
x = mario.x
y = mario.y
print(x)
print(y)
bgX = 0
bgY = 0
vel = 5
jumpCount = 10
Exemplo n.º 12
0
    def play(self):
        
        global OBJECTS, BULLETS, ENEMY_BULLETS, ENEMY_TANKS, TANK, ENEMY_TANK, ENEMY_TANKS, BRIDGE_OBJS, BRICK_OBJS, STEEL_OBJS, WATER_OBJS, GRASS_OBJS

        OBJECTS = Group()
        BULLETS = Group()
        ENEMY_BULLETS = Group()
        ENEMY_TANKS = Group()

        BRIDGE_OBJS, BRICK_OBJS, STEEL_OBJS, WATER_OBJS, GRASS_OBJS = Group(), Group(), Group(), Group(), Group()

        for i in range(0, GRID_X):
            for j in range(0, GRID_Y):
                if MAP[j][i] == GROUND:
                    continue

                if MAP[j][i] == BRIDGE:
                    new_obs = Obstacles(MAP[j][i], (i, j))
                    BRIDGE_OBJS.add(new_obs)
                elif MAP[j][i] == BRICK:
                    new_obs = Obstacles(MAP[j][i], (i, j))
                    BRICK_OBJS.add(new_obs)
                elif MAP[j][i] == STEEL:
                    new_obs = Obstacles(MAP[j][i], (i, j))
                    STEEL_OBJS.add(new_obs)
                elif MAP[j][i] == WATER:
                    new_obs = Obstacles(MAP[j][i], (i, j))
                    WATER_OBJS.add(new_obs)
                elif MAP[j][i] == GRASS:
                    new_obs = Obstacles(MAP[j][i], (i, j))
                    GRASS_OBJS.add(new_obs)
                elif MAP[j][i] == ALLIED_TANK_SYM:
                    TANK = Tank(UP, (i, j), PRO, ALLIED_TANK)
                elif MAP[j][i] == ENEMY_TANK_SYM:
                    ENEMY_TANK = EnemyTank(UP, (i, j), ANTA)
                    ENEMY_TANKS.add(ENEMY_TANK)
                    OBJECTS.add(ENEMY_TANK)
        
        OBJECTS.add(TANK)

        period_sum = 0

        commands = []
        with open("commands", "wb") as file:
            pickle.dump(commands, file)


        while self.game_stage == self.PLAY:
            dt = clock.tick(60)
            # Game play
            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()
                if event.type == pygame.KEYDOWN:
                    pressing = pygame.key.get_pressed()
                    if pressing[pygame.K_s]:
                        start_record_thread = Thread(target=self.app.start_recording)        
                        start_record_thread.start()
                        print("start recording")
                    elif pressing[pygame.K_f]:
                        stop_record_thread = Thread(target=self.app.stop_recording)
                        stop_record_thread.start()
                        print("stop recording")

            period_sum += dt
            if period_sum > 250:
                period_sum = 0
                with open("commands", "rb") as file:
                    commands = pickle.load(file)

                for command in commands:
                    if command == DOWN:
                        TANK.command_move(DOWN)
                    elif command == UP:
                        TANK.command_move(UP)
                    elif command == LEFT:
                        TANK.command_move(LEFT)
                    elif command == RIGHT:
                        TANK.command_move(RIGHT)
                    elif command == SHOOT:
                        TANK.fire(BULLETS)

                commands = []
                with open("commands", "wb") as file:
                    pickle.dump(commands, file)

            SCREEN.fill(BLACK)

            BRIDGE_OBJS.update()
            BRICK_OBJS.update()
            STEEL_OBJS.update()
            WATER_OBJS.update()

                    

            BULLETS.update(ENEMY_TANKS)
            ENEMY_BULLETS.update([TANK])

            TANK.update(ENEMY_TANKS)

            if TANK.is_dead():
                self.game_stage = self.GAMEOVER

            ENEMY_TANKS.update([TANK])

            enemy_tank_dead = 0
            for enemy_tank in ENEMY_TANKS:
                if enemy_tank.is_dead():
                    enemy_tank_dead += 1;
            if enemy_tank_dead == len(ENEMY_TANKS):
                self.game_stage = self.GAMEOVER

            GRASS_OBJS.update()

            pygame.display.flip()
Exemplo n.º 13
0
def level(window, screen):
    global best_score
    score_font = Font("fonts/freesansbold.ttf", 50)
    scores_screen = Surface((640, 50))
    done = True
    hero = Bird(80, 120, "bird/red_bird_patern.png")
    timer = Clock()

    #initial list of seeds
    seed = list()
    seed_len = 3
    seed_first = 0
    for i in range(3):
        seed.append(random.randint(0, 50))

    #initialing Group of obstacles
    obgroup = Group()
    obgroup.add(Block(640, directions.up, seed[0]))
    obgroup.add(Block(640, directions.down, seed[0]))
    obgroup.add(Block(840, directions.up, seed[1]))
    obgroup.add(Block(840, directions.down, seed[1]))
    obgroup.add(Block(1040, directions.up, seed[2]))
    obgroup.add(Block(1040, directions.down, seed[2]))
    obgroup.add(Enemy(1240))

    #music
    mixer.init()
    mixer.pre_init(44100, -16, 1, 600)
    mixer.music.load("bird/music/music.ogg")
    mixer.music.play(-1)

    while done and not hero.end:
        for e in event.get():
            if e.type == QUIT:
                done = False
            if (e.type == KEYDOWN
                    and e.key == K_SPACE) or mouse.get_pressed() == (1, 0, 0):
                hero.up = True
                jump_sound = mixer.Sound("bird/music/jump.ogg")
                jump_sound.play()
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                hero.end = True
                done = False

        picture = Background("bird/background_2.png", (0, 0))
        picture.draw(screen)
        scores_screen.fill((50, 50, 50))
        hero.update()

        col = spritecollideany(hero, obgroup)
        if col is not None:
            hero.end = True

        drinks = obgroup.sprites()
        for pepsi in drinks:
            pepsi.per(hero)
        obgroup.update(hero)
        obgroup.draw(screen)
        coca_cola = drinks[0]

        if coca_cola.rect.x + 50 < 0:
            if isinstance(coca_cola, Block):
                seed[seed_first] = random.randint(0, 50)
                obgroup.add(
                    Block(coca_cola.rect.x + 800, directions.up,
                          seed[seed_first]))
                obgroup.add(
                    Block(coca_cola.rect.x + 800, directions.down,
                          seed[seed_first]))
                drinks[0].kill()
                drinks[1].kill()

            elif isinstance(coca_cola, Enemy):
                obgroup.add(Enemy(coca_cola.rect.x + 800))
                coca_cola.kill()

        hero.draw(screen)
        scores_screen.blit(
            score_font.render(
                str(hero.score) + "  Best score: " + str(best_score), 1,
                (255, 255, 255)), (0, 0))
        window.blit(screen, (0, 50))
        window.blit(scores_screen, (0, 0))
        update()

        timer.tick(35)

    if hero.end:
        mixer.music.stop()
    if not hero.end:
        mixer.music.play(-1)

    if best_score < hero.score:
        best_score = hero.score
        win = mixer.Sound("bird/music/win.ogg")
        win.play()

    return done
Exemplo n.º 14
0
mixer.pre_init(44100, -16, 3, 512)
mixer.init()

# Параметры экрана
SIZE = [1200, 720]
FPS = 65
GRAVITY_POWER = 1.5
SCORE = 0

# Таймеры
BLINKING_RECT = USEREVENT + 1
set_timer(BLINKING_RECT, 10 * 80)

# Параметры спрайтов
ALL_SPRITES = Group()  # Все спрайты
BULLETS = Group()  # Спрайты пуль
ENEMY_BULLETS = Group()  # Спрайты вражеских пуль
MOBS = Group()  # Спрайты мобов
PLATFORMS = Group()  # Спрайты плаформ
STAIRS = Group()  # Спрайты лестниц
SPIKES = Group()  # Спрайты шипов
BONUS_BALLS = Group()  # Спрайты бонусных шаров
HEAL_CUPSULES = Group()  # Спрайты банок со здоровьем
BOSSES = Group()  # Спрайты боссов

# Пареметры и спрайты игрока
JUMP_POWER = 4
MEGAMAN_STAND = [
    load(f'data/Sprites/Megaman sprites/{i}.png')
    for i in ['standing', 'blink']
Exemplo n.º 15
0
    def get_day_items(self):
        self.npc_sprites = Group()
        self.pickups = Group()

        if self.day == 0:
            # show the newcomers around
            self.npc_sprites = Group([
                NpcFollower(WIDTH * 3 / 2 - 50, HEIGHT * 3 / 2 - 50),
                NpcFollower(WIDTH * 3 / 2 - 70, HEIGHT * 3 / 2 - 70),
                NpcFollower(WIDTH * 3 / 2 - 55, HEIGHT * 3 / 2 - 100),
                NpcFollower(WIDTH * 3 / 2 - 100, HEIGHT * 3 / 2 - 60),
                NpcFollower(WIDTH * 3 / 2 + 25, HEIGHT * 3 / 2 + 55),
                NpcFollower(WIDTH * 3 / 2 + 50, HEIGHT * 3 / 2 + 100)
            ])

        if self.day == 1:
            # dig the grave
            self.npc_sprites = Group([NpcQuester()])
            self.pickups = Group([
                pickupables.Shovel(1770, 480),
                *[pickupables.Flower(3000 + (i * 100), 700) for i in range(6)],
            ])

        if self.day == 2:
            # make lemonade
            self.npc_sprites = Group([Susan(), NpcQuester()])
            self.pickups = Group([
                pickupables.Lemon(1860, 1650),
                pickupables.EmptyBucket(2000, 590),
                pickupables.Sugar(1850, 1555),
                pickupables.RatPoison(1922, 1545),
            ])

        if self.day == 3:
            # do laundry
            self.npc_sprites = Group([NpcQuester()])
            self.pickups = Group([
                pickupables.EmptyBucket(2000, 590),
                pickupables.Soap(2000, 525),
                pickupables.RedSock(1900, 500),
                pickupables.DirtyRobes(1900, 500),
            ])

        if self.day == 4:
            # make candles
            self.npc_sprites = Group([NpcQuester()])
            self.pickups = Group([
                pickupables.EmptyBucket(2000, 590),
                pickupables.BeesWax(1890, 510),
                pickupables.BlackDye(1930, 515),
                pickupables.EssenceOfCinnamon(1970, 510),
            ])

        if self.day == 5:
            # edit prayer sheet
            self.npc_sprites = Group([NpcQuester()])

        if self.day == 6:
            # summoning ritual
            self.npc_sprites = Group(
                [NpcQuester(),
                 CultLeader(3000, 1500, self),
                 Pentagram()])

        return self.npc_sprites, self.pickups
Exemplo n.º 16
0
def game_run():
    file = r'activation.mp3'
    # Initialize
    pygame.mixer.init()
    # Load the file pf music
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()

    # Initialize and create screen.
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Aircraft war")

    # Create play button
    play_button = Button(setting, screen, 'Play', 200)
    help_button = Button(setting, screen, 'Help', 400)

    # Draw a rocket.
    rocket = Rocket(setting, screen)

    # Set a Group for bullets.
    bullets = Group()

    # Set a Group for alien bullets.
    alien_bullets = Group()

    # Set a Group for aliens.
    aliens = Group()

    # Create aliens.
    functions.create_aliens(setting, screen, rocket, aliens, alien_bullets)

    # Create States.
    states = States(setting)

    # Create Scoreboard.
    scoreboard = Scoreboard(setting, screen, states)

    # Create Textbox.
    textbox = Textbox(setting, screen)

    # Create Incidents.
    incidents = Group()

    # Create Background.
    BackGround = Background('background.jpg', [0, 0])

    # Main loop.
    while True:
        functions.respond_events(setting, screen, states, scoreboard, rocket,
                                 aliens, bullets, alien_bullets, play_button,
                                 help_button, textbox, incidents)
        if states.game_active:
            rocket.update_rocket()
            bullets.update(rocket)
            alien_bullets.update(setting)
            incidents.update(states)
            functions.update_bullets(setting, screen, states, scoreboard,
                                     rocket, aliens, bullets, alien_bullets)
            functions.update_aliens(setting, screen, states, scoreboard,
                                    rocket, aliens, bullets, alien_bullets,
                                    incidents)
            functions.update_alien_bullets(setting, screen, states, scoreboard,
                                           rocket, aliens, bullets,
                                           alien_bullets, incidents)
            functions.update_incidents(setting, screen, states, scoreboard,
                                       rocket, aliens, bullets, alien_bullets,
                                       incidents)
        functions.screen_update(setting, screen, states, scoreboard, rocket,
                                aliens, bullets, alien_bullets, play_button,
                                help_button, textbox, incidents)
        screen.fill([255, 255, 255])
        screen.blit(BackGround.image, BackGround.rect)
Exemplo n.º 17
0
from ball import Ball

from settings import Settings

from random import randint

from pygame.sprite import Group

from game_stats import Stats

from button import Button

screen = pygame.display.set_mode((1200, 600))  #创建一个窗口
pygame.display.set_caption('rabbit_head')  #窗口名
ai_settings = Settings()
balls = Group()
ships = Group()
ship = Ship(screen, ai_settings)
ships.add(ship)
ball = Ball(screen, ai_settings)
stats = Stats(ai_settings)
msg = 'play'
button = Button(ai_settings, screen, msg)
while True:

    #监视鼠标和电脑事件
    rf.check_events(ai_settings, stats, button, ship, balls)
    #背景色填充屏幕
    screen.fill(ai_settings.bg_color)

    #更新屏幕上的图像并切换到新屏幕
Exemplo n.º 18
0
def run_game():
    #Initialize game and create a screen object.
    pygame.init()
    settings = Settings()
    g.settings = Settings()

    g.settings_g = Settings()

    pygame.display.set_caption(settings.title)

    # Initialize Map
    grid = Grid(settings)
    g.tiles = Group()

    # Map Matrix initialisieren und Tiles hinzufügen
    tiles_init(settings, g.tiles)

    #Player
    fighter_comp = Fighter(hp=30,
                           defense=2,
                           power=5,
                           death_function=gf.player_death)
    g.player = GameObject(settings,
                          "player",
                          1,
                          1,
                          colors.gold,
                          img=r.player,
                          blocks=True,
                          fighter=fighter_comp)

    # Create Random Map
    make_map()

    # Initialize GUI and Inventory
    g.gui_elements = GUI(settings)
    g.inventory_menu = InventoryMenu(settings)

    #Print Welcome Message
    print_message("Welcome to the BEIDL", colors.black, colors.dark_red)

    #Initialize groups
    g.monster_group = Group()
    g.item_group = Group()
    g.dead_group = Group()
    g.inventory = Group()
    g.graphics_group = Group()
    """F**K AROUND"""
    #vvvvvvvvvvv#

    for i in range(10):
        testi_place_objects('item')

    for i in range(50):
        testi_place_objects('enemy')

    # """Test: Dummy Walls"""
    # g.map_matrix[4][5].blocked = True
    # g.map_matrix[4][5].block_sight = True
    # g.map_matrix[4][6].blocked = True
    # g.map_matrix[4][6].block_sight = True
    #
    # g.map_matrix[15][21].blocked = True
    # g.map_matrix[15][21].block_sight = True
    # g.map_matrix[16][21].blocked = True
    # g.map_matrix[16][21].block_sight = True

    #^^^^^^^^^#
    """F**K AROUND"""

    # Start the main loop for the game.
    while True:
        """MENU"""
        # Menu Screen
        #while settings.game_state == "menu":
        #gf.check_events_menu(settings, all_groups)
        #gf.update_screen_menu(settings, all_groups)
        """GAME"""
        #while g.game_state == "playing":
        while True:

            g.clock.tick(FPS)
            # ticks = pygame.time.get_ticks()

            gf.update_screen(settings)

            # Check game_state for Contol Setup
            # TODO game state control handling like this?
            if g.game_state == 'inventory':
                player_action = gf.controls_inventory(settings)
            else:
                player_action = gf.controls(settings, g.player)

            # Let Enemys take turns
            if g.game_state == 'playing' and player_action != "noturn":
                for obj in g.monster_group:
                    if obj.ai:
                        obj.ai.take_turn()

            # TODO Turn for using inventory item, redundant, use in game state?
            if player_action == "turn":
                for obj in g.monster_group:
                    if obj.ai:
                        obj.ai.take_turn()
Exemplo n.º 19
0
def run_game():

    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    ship = Ship(ai_settings, screen)
    bullets = Group()
    humans = Group()
    aliens = Group()
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    available_spase_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_spase_x / (2 * alien_width))
    number_rows = get_number_rows(ai_settings, ship.rect.height,
                                  alien.rect.height)
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            alien = Alien(ai_settings, screen)
            alien.x = alien_width + 2 * alien_width * alien_number
            alien.rect.x = alien.x
            aliens.add(alien)

            #    print(alien.rect.y)

            create_alien(ai_settings, screen, aliens, alien_number, row_number)
    # aliens.add(alien)

    bg_color = (20, 250, 200)
    while True:
        for event in pygame.event.get():

            #for event in pygame.event.get():

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    human = Human(ai_settings, screen)
                if event.key == pygame.K_1:
                    first = randint(0, 220)
                    second = randint(0, 220)
                    three = randint(0, 220)
                    ai_settings.bg_color = (first, second, three)
                if event.key == pygame.K_b:
                    sys.exit()
                if event.key == pygame.K_RIGHT:

                    ship.movin_right = True
                if event.key == pygame.K_SPACE:
                    if len(bullets) < ai_settings.bullet_allowed:

                        new_bullet = Bullet(ai_settings, screen, ship)
                        bullets.add(new_bullet)

                if event.key == pygame.K_LEFT:
                    ship.movin_left = True
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    ship.movin_right = False
                if event.key == pygame.K_LEFT:
                    ship.movin_left = False
                if event.key == pygame.K_SPACE:

                    new_bullet = Bullet(ai_settings, screen, ship)
                    bullets.add(new_bullet)
        ship.update()
        bullets.update()
        for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                bullets.remove(bullet)

        screen.fill(ai_settings.bg_color)
        for bullet in bullets.sprites():
            bullet.draw_bullet()
            first = randint(0, 200)
            second = randint(0, 200)
            three = randint(0, 200)
            ai_settings.bullet_color = (first, second, three)

            collisions = pygame.sprite.groupcollide(bullets, aliens,
                                                    bullets_die, True)

        ship.blitme()
        aliens.draw(screen)
        alien.blitme()
        aliens.update()
        humans.update()
        pygame.display.flip()
Exemplo n.º 20
0
    def run_game():
        global ch, dobollet, db, wea, t
        pygame.init()
        pygame.mixer.init()
        shoot = mixer.Sound("C:\windows\media\Ring02.wav")
        music = mixer.Sound("sounds/Windows Critical Stop.wav")
        image = pygame.image.load('bg.gif')

        turn = 0

        ch = 10

        fg = 1
        pfg = 1
        joysticks = [
            pygame.joystick.Joystick(x)
            for x in range(pygame.joystick.get_count())
        ]
        print(joysticks.pop(1))
        for joystick in joysticks:
            joystick.init()
        i = 0

        j = False
        sit = False
        sco = 0

        ai_settings = Settings()
        screen = pygame.display.set_mode(
            (ai_settings.screen_width, ai_settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        ship = Ship(ai_settings, screen)
        bullets = Group()

        ships = Group()
        blocks = Group()
        aliens = Group()
        l = 0
        r = 0
        godown = 0
        sb = Scoreboard(ai_settings, screen, 0, sco)
        alies = Group()
        buttons = Group()
        yu = False
        #rint(ship.y)iii
        alienbullets = Group()
        ert = 0
        tr = [
            1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0, 0, 1, 1, 1, 1, 0,
            0, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
            1, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
            1, 2
        ]
        sty = Group()
        uii = 0
        do_liberint(pygame, Block, blocks, ai_settings, screen, 'liberint.txt',
                    Alien, aliens)
        upup = 0
        ship2 = Ship(ai_settings, screen)
        for alien in aliens.sprites():
            alien.image = pygame.image.load('bomb.gif')
        poweraps = Group()
        aiens = Group()
        ant = Ant_men(ai_settings, screen, ship)
        ships.add(ship)
        ships.add(ship2)
        shoot.play(-1)
        time = 0
        un = 0
        while True:

            if r == 0:
                #ship.imageship.image = pygame.image.load('SCrightup.gif')
                ship.blitme()
                #pygame.display.flip()

                for alien in blocks.sprites():

                    alien.x -= 1
                    alien.rect.x = alien.x
                #pygame.display.flip()
                #pygame.display.flip()
                #pygame.display.flip()
                #ship.image = pygame.image.load('SCright.gif')
                ship.blitme()
                # if pygame.sprite.spritecollideany(ship,blocks):
                #     for alien in poweraps.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x
                #     for alien in blocks.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x

            if l == 0:

                #                ship.image = pygame.image.load('SCleftup.gif')

                #pygame.display.flip()

                for alien in blocks.sprites():

                    alien.x += 1
                    alien.rect.x = alien.x
                #pygame.display.flip()
                #pygame.display.flip()
                #pygame.display.flip()

                #ship.blitme()
                # if pygame.sprite.spritecollideany(ship,blocks):
                #     for alien in poweraps.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x
                #     for alien in blocks.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x

            if r == 0:

                ant.x -= 1
                ant.rect.x = ant.x
                # if pygame.sprite.spritecollideany(ship,blocks):
                #     for alien in poweraps.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x
                #     for alien in blocks.sprites():
                #         alien.x += 1
                #         alien.rect.x = alien.x

            if l == 0:

                ant.x += 1
                ant.rect.x = ant.x  # if pygame.sprite.spritecollideany(ship,blocks):
                #     for alien in poweraps.sprites():
                #         alien.x -= 1
                #         alien.rect.x = alien.x
                #     for alien in blocks.sprites():
                #         alien.x -= 1
                #         alien.rect.x = alien.x

            for event in pygame.event.get():

                #for event in pygame.event.get():

                # #                if event.type == pygame.KEYDOWN:
                #                     if event.key == pygame.K_1:
                #                         first = randint(0,220)
                #                         second = randint(0,220)
                #                         three = randint(0,220)
                #                         ai_settings.bg_color = (first,second,three)
                #                     if event.key == pygame.K_b:
                #                         sys.exit()
                #                     if event.key == pygame.K_RIGHT:

                #                         #ship.movin_right = True
                #                         cr = 0
                #                         t = 2
                #                     if event.key == pygame.K_LEFT:
                #                         #ship.movin_left = True
                #                         cl = 0
                #                         t = 3
                # if event.key == pygame.K_r:
                #     #ship.movin_left = True
                #     if len(bullets) <= bulets:
                #         new_bullet = Bullet(ai_settings,screen,ship,aliens,bullets,0)
                #         bullets.add(new_bullet)
                # if event.key == pygame.K_UP:

                #     cu = 0
                #     t = 0
                if event.type == pygame.MOUSEBUTTONDOWN:
                    xy, yx = pygame.mouse.get_pos()
                    blok = Block(ai_settings, screen, 'fkdf')
                    blok.rect.x, blok.rect.y = xy, yx
                    blok.x, blok.y = xy, yx
                    blocks.add(blok)
                if event.type == pygame.JOYAXISMOTION:
                    buttons = joystick.get_numaxes()
                    for i in range(buttons):
                        but = joystick.get_axis(0)

                        if but < -.5:

                            ship.x -= 1
                            ship.rect.x = ship.x
                            t = 3
                        but = joystick.get_axis(0)
                        if but > .5:

                            ship.x += 1
                            ship.rect.x = ship.x

                            t = 2
                        but = joystick.get_axis(1)
                        if but < -.5:
                            ship.y -= 1
                            ship.rect.y = ship.y
                        if but > .5:
                            ship.y += 1
                            ship.rect.y = ship.y

                        # but = joystick.get_axis(1)
                        # if but <  -.5:

                        #     ship.y -= 1
                        #     ship.rect.y = ship.y
                        #     if pygame.sprite.spritecollideany(ship,blocks):
                        #         ship.y += fuster
                        #         ship.rect.y = ship.y

                        #     t = 0
                        # but = joystick.get_axis(1)
                        # if but > .5:

                        #     ship.y += 1
                        #     ship.rect.y = ship.y
                        #     if pygame.sprite.spritecollideany(ship,blocks):
                        #         ship.y -= fuster
                        #         ship.rect.y = ship.y
                        #     t = 1

                buttons = joystick.get_numhats()
                for i in range(buttons):
                    but = joystick.get_hat(i)
                    if but == (-1, 0):

                        ship.rect.x -= 1
                    but = joystick.get_hat(i)
                    if but == (1, 0):
                        ship.rect.x += 1
                    but = joystick.get_hat(i)

                    if but == (0, -1):

                        ship.rect.y -= 1
                    but = joystick.get_hat(i)
                    if but == (0, 1):

                        ship.rect.y += 1
                    but = joystick.get_hat(i)
                    print(but)
                    #if but == (0,1):

                    #     j = False
                    #     pfg *=-1
                    #     j = True
                    # but = joystick.get_hat(i)

                if event.type == pygame.JOYBUTTONDOWN:
                    buttons = joystick.get_numbuttons()
                    for button in range(buttons):
                        # # print(button)
                        # #pass
                        # # if button == (0,0):
                        # #     music.play()

                        # #     new_bullet = Bullet(ai_settings,screen,ship,aliens,bullets,alien,t)
                        # #     bullets.add(new_bullet)
                        but = joystick.get_button(0)
                        if but:
                            j = False
                            pfg *= -1
                            j = True
                        but = joystick.get_button(2)
                        if but:

                            if upup == 0:

                                upup = 1
                                break
                            if upup == 1:

                                upup = 0
                                break

                        #print(but)

                        # if but == 2:

                        #     j = False
                        #     pfg *=-1
                        #     j = True
                        # but = joystick.get_button(button)
                        # if but == 1:
                        #     upup = 1

                elif event.type == pygame.JOYBUTTONUP:
                    #buttons = joystick.get_numbuttons()
                    buttons = joystick.get_numbuttons()
                    for button in range(buttons):
                        # # print(button)
                        # #pass
                        # # if button == (0,0):
                        # #     music.play()

                        # #     new_bullet = Bullet(ai_settings,screen,ship,aliens,bullets,alien,t)
                        # #     bullets.add(new_bullet)

                        but = joystick.get_button(2)
                        if but:
                            upup = 0

                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_LEFT:

                        cl2 = 0
                        cr2 = 1
                        cu2 = 1
                        cd2 = 1
                        t2 = 3

                    if event.key == pygame.K_RIGHT:

                        cl2 = 1
                        cr2 = 0
                        cu2 = 1
                        cd2 = 1
                        t2 = 2
                        #but = joystick.get_hat(i)
                    if event.key == pygame.K_DOWN:

                        cl2 = 1
                        cr2 = 1
                        cu2 = 1
                        cd2 = 0
                        t2 = 1
                    #but = joystick.get_hat(i)
                    if event.key == pygame.K_UP:

                        cl2 = 1
                        cr2 = 1
                        cu2 = 0
                        cd2 = 1
                        t2 = 0
                    if event.key == pygame.K_v:
                        new_bullet = Bullet(ai_settings, screen, ship2, aliens,
                                            bullets, alien, t2)
                        bullets.add(new_bullet)

#                 elif event.type == pygame.KEYUP:
#                     if event.key == pygame.K_RIGHT:

#                         ship.movin_right = False
#                         cr = 1

#                     if event.key == pygame.K_LEFT:
#                         ship.movin_left = False
#                         cl = 1
#                     if event.key == pygame.K_UP:

#                         cu = 1

#                     if event.key == pygame.K_DOWN:
#                         cd = 1
#                     if event.key == pygame.K_2:
#                         ship.image = pygame.image.load(random.choice(images))
#                     if event.key == pygame.K_DOWN:
#                         ship.movin_down = False
# #276
#276
            ship.update(blocks, ship)

            bullets.update(bullets, aliens)
            collisions = pygame.sprite.groupcollide(ships, aliens, False, True)

            #print('you lose')
            #break
            ship.blitme()

            # if pygame.sprite.spritecollideany(ship,blocks):

            #     for alien in blocks.sprites():
            #         alien.y += 1
            #         alien.rect.y = alien.y
            #     ant.y += 1
            #     ant.rect.y = ant.y

            #    godown = 0
            #           pygame.display.flip()
            for bullet in bullets.copy():
                if bullet.rect.bottom <= 0 or bullet.rect.bottom >= 900 or bullet.rect.centerx <= 0 or bullet.rect.centerx >= 1000:
                    bullets.remove(bullet)

            screen.fill(ai_settings.bg_color)
            # for bullet in alienbullets.copy():
            #     if bullet.rect.bottom >= 900:
            #         bullets.remove(bul
            # screen.fill(ai_settings.bg_color)

            # for bullet in alienbullets.sprites():

            #     bullet.draw_bullet()

            #     first = randint(0,200)
            #     second = randint(0,200)
            #     three = randint(0,200)
            #     ai_settings.bullet_color = (first,second,three)
            #     collisins = pygame.sprite.groupcollide(blocks,bullets,True,True)
            collisions = pygame.sprite.groupcollide(ships, poweraps, False,
                                                    True)
            if len(aliens) <= 0:
                print('you win')
                break

            # for alien in aliens.sprites():

            #     if pygame.sprite.spritecollideany(alien,blocks):
            #         alien.duraction *= -1
            for bullet in bullets.sprites():

                bullet.draw_bullet()
                collisions = pygame.sprite.groupcollide(
                    bullets, aliens, True, True)
                if collisions:
                    moneys += 1

                collisions = pygame.sprite.groupcollide(
                    bullets, blocks, True, False)

                first = randint(0, 200)
                second = randint(0, 200)
                three = randint(0, 200)
                ai_settings.bullet_color = (first, second, three)

            bullets.update(bullets, aliens)
            ship.blitme()
            #chekupdown_fleet_edges(ai_settings,aliens)
            #alien.blitme()
            bullets.draw(screen)
            sb.show_score()
            alienbullets.update(bullets, aliens)
            collisions = pygame.sprite.groupcollide(ships, aliens, False, True)
            aliens.draw(screen)

            #if un == 0:

            blocks.draw(screen)
            blocks.update()
            if pygame.sprite.spritecollideany(ant, ships):
                if pfg == -1:
                    g = 1

                    bullets.empty()
                    ch -= 1
                    if ch <= 0:
                        ant.image = pygame.image.load('bowserflat.gif')
                        un = 1
                    #    print('you win')
                    #    break

                    j = False
                    pfg *= -1

                    j = True
                else:
                    if un == 0:
                        print('you lose')
                        sys.exit()

            if pygame.sprite.spritecollideany(ant, bullets):
                ch -= 1
                bullets.empty()
                if ch <= 0:

                    print('you win')
                    break
            bullets.update(0, 0)
            bullets.draw(screen)
            ship2.blitme()
            #if bezero == 34:
            #bezero = 0

            #sb.show_score()
            #poweraps.draw(screen)
            #pygame.display.update()
            #screen.blit(image,(0,0))
            pygame.display.flip()
Exemplo n.º 21
0
def run_game():
    seconds = 0
    pygame.init()
    bulletCollidedWithBunker = False
    alienCollidedWithBullet = False
    ai_settings = Settings()
    bunkerRect = 0

    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings,screen,"Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings,screen,stats)
    ship = Ship(ai_settings,screen)
    bullets = Group()
    aliens = Group()
    numberOfTicks = 0








    bunker = pygame.image.load("images/bunker1.png")
    bunkerCopy = bunker
    del bunker


    print("bunker clipping area")
















    print("bunker's size")





































    gf.create_fleet(ai_settings, screen,ship, aliens)

    bg_color = (230, 230, 230)

    while True:








        pygame.display.update()


































        gf.check_events(ai_settings,screen,stats,sb,play_button,ship,aliens,bullets,bunkerCopy)



        gf.update_screen(ai_settings, screen,stats,sb, ship, aliens, bullets, play_button,bunkerCopy)








        if stats.game_active:

          pygame.draw.circle(screen,(0,0,255),(130,242 ),5,5)

          pygame.display.update()

          ship.update()


          if bulletCollidedWithBunker == False:
           gf.update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets,bunkerGroup,bunkerCopy)
           gf.update_aliens(ai_settings,screen,stats,sb,ship,aliens, bullets)



        if bulletCollidedWithBunker == False:
          bullets.update()




         #118,255,3,255


        for bunker12 in bunkerGroup:







































         for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                 bullets.remove(bullet)
Exemplo n.º 22
0
            #计算子表面框架在剪切时所处的位置.即大小
            self.frame_rect.x = (self.frame % 4) * self.frame_rect.width
            self.frame_rect.y = (self.frame // 4) * self.frame_rect.height
            self.old_frame = self.frame

        self.image = self.mast_image.subsurface(self.frame_rect)  #这里就是在生成子表面


pygame.init()
screen = pygame.display.set_mode((800, 600))
color = (255, 255, 255)
mysprite = Mysprite()

print(mysprite.last_frame)  #打印出最后一个子表面的位置。

group = Group()
group.add(mysprite)
tick = pygame.time.Clock()

mrunning = True
while mrunning:
    tick.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mrunning = False

    screen.fill(color)
    group.update()
    group.draw(screen)
    pygame.display.update()
Exemplo n.º 23
0
    load(f'Megaman sprites/megaman walk right {i}.png') for i in [2, 3, 2, 4]
]
WALK_LEFT_ANIM = [
    load(f'Megaman sprites/megaman walk left {i}.png') for i in [2, 3, 2, 4]
]
STAND_RIGHT_ANIM = [
    load('Megaman sprites/megaman standing right.png'),
    load('Megaman sprites/megaman blink right.png')
]
STAND_LEFT_ANIM = [
    load('Megaman sprites/megaman standing left.png'),
    load('Megaman sprites/megaman blink left.png')
]
JUMP_LEFT = load('Megaman sprites/Megaman jump left.png')
JUMP_RIGHT = load('Megaman sprites/Megaman jump right.png')
STAND_AND_SHOT_R = load('Megaman sprites/megaman shot right.png')
STAND_AND_SHOT_L = load('Megaman sprites/megaman shot left.png')

# for bullets
BULLET_SPEED = 15
BULLET_DAMAGE = 10

# for all
BULLETS = Group()
MOBS = Group()
PLATFORMS = Group()
ALL_SPRITES = Group()

TOTAL_LEVEL_WIDTH = 0
TOTAL_LEVEL_HEIGHT = 0
Exemplo n.º 24
0
def run_game():
	# 初始化游戏并创建一个屏幕对象
	pygame.init()

	ai_settings = Settings()
	screen = pygame.display.set_mode((
		ai_settings.screen_width, ai_settings.screen_height)) # 设置的窗口大小

	pygame.display.set_caption("Alien Invasion") # 窗口标题

	# 创建Play按钮
	play_button = Button(ai_settings, screen, "PLAY")

	# 创建一个计分板
	counter = '0'
	record_border = Record(ai_settings, screen)


	# 创建一艘飞船
	ship = Ship(ai_settings, screen)

	# 创建一个外星人
	aliens = Group()

	# 创建一个用于储存子弹的编组
	bullets = Group()
	localtime = time.localtime(time.time())
	localtime = time.strftime('%S', localtime)
	localtime = int(localtime)
	counter = 0

	# 创建一个用于储存游戏统计信息的实例
	stats = GameStats(ai_settings)
	# 开始游戏的主循环
	while True:

		# 当游戏尚未开始时,持续记录系统时间,当开始后则开始正常系统运行,跳过此项
		localtime = gf.get_localtime(stats, localtime)

		# 监视键盘和鼠标的事件
		gf.check_event(ai_settings, screen, ship, bullets, 
			stats, play_button, aliens)


		if stats.game_active:

		# 生成外星人,每5秒生成一只外星人
			localtime = gf.show_aliens(ai_settings, aliens, screen,
		 localtime, counter)


			#创建好飞船之后更新飞船的坐标
			ship.update()
			# 实时更新子弹的坐标
			gf.update_bullets(aliens, bullets, record_border)
			# 实时更新外星人的坐标
			gf.update_aliens(ai_settings, stats, screen, 
				ship, aliens, bullets, record_border)
			
			# 在飞船生命用完之后,持续记录本地时间,不然无法生成新的外星人
			if ai_settings.dead_alive == True:
				# 飞船死亡
				current_time = time.localtime(time.time())
				current_time = time.strftime('%S', current_time)
				current_time = int(current_time)
				localtime = current_time
				# 避免无法生成新的外星人
				if localtime >= 57:
					localtime = 0
				ai_settings.dead_alive = False


		# 刷新屏幕
		gf.update_screen(ai_settings, screen, stats, ship, 
			bullets, aliens, play_button, record_border)
Exemplo n.º 25
0
    def __init__(self, font_dict):

        #Bumper prototypes, centered on x axis if LR or y axis if TB
        #Coordinates are so the short wall is first
        self.left_bumper = [
            np.array([15, -80]),
            np.array([15, 80]),
            np.array([0, 95]),
            np.array([0, -95])
        ]
        self.right_bumper = [
            np.array([-15, -80]),
            np.array([-15, 80]),
            np.array([0, 95]),
            np.array([0, -95])
        ]
        self.top_bumper = [
            np.array([-80, 15]),
            np.array([80, 15]),
            np.array([95, 0]),
            np.array([-95, 0])
        ]
        self.bottom_bumper = [
            np.array([-80, -15]),
            np.array([80, -15]),
            np.array([95, 0]),
            np.array([-95, 0])
        ]

        self.fonts = font_dict

        self.ball_surf_w = 450
        self.ball_surf_h = 225
        self.ball_surf_origin = self.x_orig, self.y_orig = 95, 80
        self.ball_surf = pygame.surface.Surface(
            [self.ball_surf_w, self.ball_surf_h],
            pygame.SRCALPHA)  #Legal area of ball to roll

        #self.ball_surf_origin = ball_surf_origin

        self.play_surface = self.ball_surf.get_rect()
        #self.play_surface = ball_surf_rect

        self.scratch = TextDisplay(self.fonts["stencil_50"],
                                   "Scratch",
                                   display_time=750)

        self.strokes = 0

        self.score = TextDisplay(self.fonts["century_15"],
                                 "Strokes: " + str(self.strokes))
        self.score_size = self.score.get_message().get_size()
        self.score.display()

        self.bumper_coords = self.generate_bumper_coords(self.play_surface)
        self.pockets = Group(self.__initalize_pockets())
        self.cue_ball = CueBall([375, 100],
                                initial_vel=pm.Vector2(0, 0),
                                friction=0.01)
        self.balls = Group(self.__initialize_balls(), self.cue_ball)  #care
        self.stick = Stick(self.ball_surf_origin)
        self.update_stick = True

        self.sunk_stack = [
            PoolBall([0, 0], num=np.Inf)
        ]  #Contains balls sunk and the order they were sunk in. Dummy ball at bottom
        self.last_sunk = None  #Flag for top of stack before cue_ball was sunk. In case of scratch, pop down
        #sunk stack until this is hit

        self.mouse_pos_on_click = None
        self.play_stick_animation = False
def run():
    # Initialization
    pygame.init()
    settings = Settings()
    state = Game_State()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Super Mario Bros")
    bg_color = settings.bg_color
    stats = Game_Stats(screen, settings)

    clock = pygame.time.Clock()

    mario = Mario(screen, settings, stats)

    pygame.mixer.music.load("Sounds/overworld.mp3")
    pygame.mixer.music.play(-1)

    # Groups
    map_group = Group()
    block_group = Group()
    floor_group = Group()
    pipe_group = Group()
    enemy_group = Group()
    powerup_group = Group()
    fireball_group = Group()
    dead_group = Group()

    map.generate_map(screen, settings, map_group, floor_group, pipe_group,
                     block_group, enemy_group)
    f = Flag(screen, settings, 198 * settings.block_width,
             13 * settings.block_height)
    f.add(map_group)

    pipesprites = pipe_group.sprites()

    timer = 0
    death_counter = 0

    # Game Loop
    while state.running:
        settings.reset_holders()
        clock.tick(settings.fps)

        # handle mario death
        if mario.is_dead and death_counter <= 240:
            # draw black screen
            if death_counter == 60:
                screen.fill(settings.bg_color)
                stats.lives -= 1
                if stats.lives < 0:
                    stats.init_base_values()
                    #display game over
                    game_over_label = Text(None, settings.TEXT_SIZE,
                                           "Game Over", settings.WHITE, 0, 0)
                    game_over_label.rect.center = (settings.screen_width / 2,
                                                   settings.screen_height / 2)
                    game_over_label.draw(screen)
                else:
                    # display level
                    lvl_str = "World " + str(stats.world) + "-" + str(
                        stats.level_num)
                    level_label = Text(None, settings.TEXT_SIZE, lvl_str,
                                       settings.WHITE, 0, 0)
                    level_label.rect.center = (settings.screen_width / 2,
                                               settings.screen_height / 2)
                    level_label.draw(screen)
                pygame.display.flip()
            death_counter += 1
            print(death_counter)
        elif mario.is_dead and death_counter > 240:
            # reset
            death_counter = 0
            mario.kill()
            mario = Mario(screen, settings, stats)
            map_group = Group()
            block_group = Group()
            floor_group = Group()
            pipe_group = Group()
            enemy_group = Group()
            powerup_group = Group()
            fireball_group = Group()
            dead_group = Group()
            pygame.mixer.music.play(-1)
            map.generate_map(screen, settings, map_group, floor_group,
                             pipe_group, block_group, enemy_group)
            f = Flag(screen, settings, 198 * settings.block_width,
                     13 * settings.block_height)
            f.add(map_group)
            stats.new_level()

        # victory -> change level -> use death_counter to reset
        if mario.has_won and death_counter <= 300:
            # draw black screen
            if death_counter == 100:
                stats.level_num += 1
                screen.fill(settings.bg_color)
                # display level
                lvl_str = "World " + str(stats.world) + "-" + str(
                    stats.level_num)
                level_label = Text(None, settings.TEXT_SIZE, lvl_str,
                                   settings.WHITE, 0, 0)
                level_label.rect.center = (settings.screen_width / 2,
                                           settings.screen_height / 2)
                level_label.draw(screen)
                coming_soon = Text(None, settings.TEXT_SIZE, "Coming Soon",
                                   settings.WHITE, 0, 0)
                coming_soon.rect.center = (settings.screen_width / 2,
                                           (settings.screen_height / 2) +
                                           settings.SPACER)
                coming_soon.draw(screen)
                pygame.display.flip()
            death_counter += 1
            print(death_counter)
        elif mario.has_won and death_counter > 300:
            # reset game
            death_counter = 0
            mario.kill()
            mario = Mario(screen, settings, stats)
            map_group = Group()
            block_group = Group()
            floor_group = Group()
            pipe_group = Group()
            enemy_group = Group()
            powerup_group = Group()
            fireball_group = Group()
            dead_group = Group()
            pygame.mixer.music.load("Sounds/overworld.mp3")
            pygame.mixer.music.play(-1)
            map.generate_map(screen, settings, map_group, floor_group,
                             pipe_group, block_group, enemy_group)
            f = Flag(screen, settings, 198 * settings.block_width,
                     13 * settings.block_height)
            f.add(map_group)
            stats.new_level()

        # Game Play
        gf.check_events(state, mario, screen, settings, fireball_group,
                        map_group)
        # Update here
        if not mario.is_dead and not mario.has_won:
            if timer < settings.fps:
                timer += 1
            else:
                timer = 0
                stats.decrement_time()

            gf.update(screen, settings, mario, map_group, floor_group,
                      pipe_group, block_group, enemy_group, powerup_group,
                      fireball_group, dead_group, f)

            if stats.did_time_runout():
                mario.dead()
            if stats.time == 100:
                pygame.mixer.Sound('Sounds/time_warning.wav').play()

            # update game values
            stats.add_score(settings.score_holder)
            stats.add_coin(settings.coin_holder)
            if settings.one_up:
                stats.lives += 1
                settings.one_up = False
            # Display here
            stats.update()
            gf.update_screen(screen, settings, stats, mario, map_group,
                             floor_group, pipe_group, block_group, enemy_group,
                             powerup_group, fireball_group, dead_group, f)
        # stats.draw()

    pygame.quit()
    sys.exit()
Exemplo n.º 27
0
def run_game():
    # Initialize pygame, settings, and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make an instance of Play button and high scores button
    play_button = Play(ai_settings, screen, "Play Space Invaders")
    high_scores = HighScore(ai_settings, screen, "High Scores")
    home_button = Back(ai_settings, screen, "Back to Home")
    main_menu = Menu(ai_settings, screen)

    # Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Make a ship, group of bullets, and group of aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    alien1 = Group()
    alien2 = Group()
    alien3 = Group()
    bunkers = Group()
    ufo = Group()

    # Create a fleet of aliens
    gf.create_fleet(ai_settings=ai_settings,
                    screen=screen,
                    ship=ship,
                    alien1=alien1,
                    alien2=alien2,
                    alien3=alien3)

    # Create bunkers
    gf.create_bunker_row(ai_settings=ai_settings,
                         screen=screen,
                         bunkers=bunkers)

    # Set up sounds
    pygame.mixer.music.load('sounds/bg_music.wav')
    music_playing = False

    # Start the main loop for the game
    while True:
        if not music_playing:
            pygame.mixer.music.play(-1, 0.0)
            music_playing = True
        gf.check_events(ai_settings=ai_settings,
                        screen=screen,
                        main_menu=main_menu,
                        stats=stats,
                        sb=sb,
                        play_button=play_button,
                        high_scores=high_scores,
                        home_button=home_button,
                        ship=ship,
                        alien1=alien1,
                        alien2=alien2,
                        alien3=alien3,
                        bullets=bullets)
        if stats.game_active:
            gf.create_ufo(ai_settings=ai_settings, screen=screen, ufo=ufo)
            ship.update()
            gf.update_bullets(ai_settings=ai_settings,
                              screen=screen,
                              stats=stats,
                              sb=sb,
                              ship=ship,
                              alien1=alien1,
                              alien2=alien2,
                              alien3=alien3,
                              bullets=bullets,
                              bunkers=bunkers,
                              ufo=ufo)
            gf.update_aliens(ai_settings=ai_settings,
                             screen=screen,
                             stats=stats,
                             sb=sb,
                             ship=ship,
                             alien1=alien1,
                             alien2=alien2,
                             alien3=alien3,
                             ufo=ufo,
                             bullets=bullets,
                             bunkers=bunkers,
                             music_playing=music_playing)

        gf.update_screen(ai_settings=ai_settings,
                         screen=screen,
                         stats=stats,
                         sb=sb,
                         ship=ship,
                         bunkers=bunkers,
                         alien1=alien1,
                         alien2=alien2,
                         alien3=alien3,
                         ufo=ufo,
                         bullets=bullets,
                         main_menu=main_menu,
                         high_scores=high_scores)
Exemplo n.º 28
0
def Game_loop():
    size = DISPLAY_WIDTH / 16.0
    posx = (DISPLAY_WIDTH - (size // 2) * 17) * 27 // 100
    posy = 0
    court = generate_court(size=size, start_posx=posx, start_posy=posy)
    snake = [(8, 18, 9), (8, 16, 8), (8, 14, 7)]
    prey = 0

    button_group = Group()
    left_button = Text(text=u'<',
                       x=5,
                       y=50,
                       size=22,
                       font_file='a_Albionic.ttf',
                       color=(250, 250, 250),
                       surface=screen)
    right_button = Text(text=u'>',
                        x=85,
                        y=50,
                        size=22,
                        font_file='a_Albionic.ttf',
                        color=(250, 250, 250),
                        surface=screen)
    button_group.add(left_button, right_button)
    menu_button = Hexagon_Button(lable=u'меню',
                                 posx=87,
                                 posy=2,
                                 font_size=3,
                                 font_file='a_Albionic.ttf',
                                 color=(35, 125, 30),
                                 text_color=(210, 205, 10),
                                 border_color=(210, 205, 10))

    wasted = Text(text=u'Потрачено!',
                  x=6,
                  y=35,
                  size=7,
                  font_file='a_Albionic.ttf',
                  color=(250, 150, 120),
                  surface=screen)
    win = Text(text=u'Победа!',
               x=20,
               y=35,
               size=14,
               font_file='a_Albionic.ttf',
               color=(250, 150, 120),
               surface=screen)
    points_label = Text(text=u'Очки: 0',
                        x=2,
                        y=2,
                        size=3,
                        font_file='a_Albionic.ttf',
                        color=(85, 170, 10),
                        surface=screen)

    fps = Text(text=u'',
               x=5,
               y=2,
               size=2,
               font_file='a_Albionic.ttf',
               color=(85, 170, 10),
               surface=screen)

    apple_eat_sound = mixer.Sound('sounds/Apple_eat.ogg')
    apple_eat_sound.set_volume(1.0)

    finally_background = Surface((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    vector = 1
    alpha = 0
    id = 8
    x = 14
    y = 7
    dt = 0
    clock = Clock()
    done = False
    while not done:
        mp = mouse.get_pos()
        for event in get():
            if event.type == QUIT:
                done = True
                continue
            if event.type == KEYDOWN:
                if vector > 0:
                    if event.key == K_LEFT:
                        vector -= 1
                    if event.key == K_RIGHT:
                        vector += 1
            if event.type == MOUSEBUTTONDOWN:
                if vector > 0:
                    if left_button.rect.collidepoint(mp):
                        vector -= 1
                    elif right_button.rect.collidepoint(mp):
                        vector += 1
                if menu_button.rect.collidepoint(mp):
                    done = True
                    continue
            if vector < 1 and vector > -1:
                vector = 6
            elif vector > 6:
                vector = 1

        if not prey:
            prey = choice(tuple(court))
            while prey.id_and_pos in snake:
                prey = choice(tuple(court))

        if dt > 400:
            dt = 0
            if vector == 1:
                x -= 2
                y -= 1
            elif vector == 2:
                x -= 1
                if x % 2 != 0:
                    y -= 1
                id += 1
            elif vector == 3:
                x += 1
                if x % 2 == 0:
                    y += 1
                id += 1
            elif vector == 4:
                x += 2
                y += 1
            elif vector == 5:
                x += 1
                if x % 2 == 0:
                    y += 1
                id -= 1
            elif vector == 6:
                x -= 1
                if x % 2 != 0:
                    y -= 1
                id -= 1

            next_step = (id, x, y)
            if next_step not in snake:
                if prey.id_and_pos != next_step:
                    snake.append(next_step)
                    snake.pop(0)
                else:
                    snake.append(next_step)
                    apple_eat_sound.play(0)
                    points_label.set_text(text=u'Очки: %s' %
                                          str(len(snake) - 3))
                    prey = 0
                    #if len(snake) > 13:
                    #    vector = -1
                    #delay(10)
            else:
                vector = -1
            if id < 0 or id > 16 or y < 0 or y > 9:
                vector = -1

        screen.fill((20, 20, 40))
        court.update(screen, snake, prey)

        if vector == -1:
            if alpha < 200:
                alpha += 3
                finally_background.set_alpha(alpha)
            screen.blit(finally_background, (0, 0))
            #if len(snake) < 12:
            #    wasted.draw()
            #else:
            #    win.draw()
            wasted.set_text(text=u'Уничтожено %s жертв!' % str(len(snake) - 3))
            wasted.draw()

        fps.set_text(u'FPS: %s' % clock.get_fps())
        fps.draw()

        button_group.draw(screen)
        menu_button.draw(screen, mp)
        points_label.draw()

        window.blit(screen, (0, 0))
        flip()
        clock.tick(40)
        dt += clock.get_tick()
Exemplo n.º 29
0
    def run_game3():
        global ch, brek, bulsets, wea, step_x, step_y, right_x_border, down_y_border
        ch = 300
        ch2 = 300
        pygame.init()
        ai_settings = Settings()
        screen = pygame.display.set_mode(
            (ai_settings.screen_width, ai_settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        ship = Ship(ai_settings, screen)
        ship2 = Ship(ai_settings, screen)
        bullets = Group()
        ship2.rect.x = 100
        ship2.rect.y = 500
        ship.rect.x = 100
        ship.rect.y = 500
        bullets2 = Group()
        aliens = Group()

        alienbullets = Group()
        alien = Alien(ai_settings, screen, alienbullets, alienBullet, ship)
        aliens.add(alien)
        alien2 = Alien(ai_settings, screen, alienbullets, alienBullet, ship2)
        aliens.add(alien2)
        pygame.time.wait(int(1000 / 60))

        #for event_type, status in joycon.events():
        #    #("ButtonEventJoyCon:")
        #    #(event_type, status)
        isstickbut = joycon.stick_r_btn
        isstickmove = joycon.stick_r
        # if isstickmove[1] > 2000:
        #     #('up')
        # elif isstickmove[1] < 2000:
        #     #('down')
        # else:
        #     #('idfujfeg')
        # if isstickmove[0] > 2000:
        #     #('right')
        # elif isstickmove[0] < 2000:
        #     #("left")
        # else:
        #     #('idfujfeg')
        libe = [1, 3, 4]
        mx, my = 0, 0
        #do_liberint(ship,Alien,aliens,ai_settings,screen,libe,'robot.gif','supercat.gif','fire.gif',pygame)
        bg_color = (20, 250, 200)
        aliens.add(alien)
        while True:

            #if wea == 1:

            # if bulsets != 1:

            #     for uytru in range(bulsets):

            #         le = Bullet(ai_settings,screen,ship,aliens,bullets)
            #         bullets.add(le)
            #         le.rect.x+=uytru*10

            #         le2 = Bullet(ai_settings,screen,ship,aliens,bullets)
            #         bullets.add(le2)
            #         le2.rect.x-=uytru*10

            if bulsets != 1:

                for uytru in range(bulsets):

                    le = Bullet(ai_settings, screen, ship, aliens, bullets)
                    bullets.add(le)
                    le.rect.x += uytru * 10

                    le2 = Bullet(ai_settings, screen, ship, aliens, bullets)
                    bullets.add(le2)
                    le2.rect.x -= uytru * 10

            for event in pygame.event.get():

                #for event in pygame.event.get():

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_1:
                        first = randint(0, 220)
                        second = randint(0, 220)
                        three = randint(0, 220)
                        ai_settings.bg_color = (first, second, three)
                    if event.key == pygame.K_b:
                        sys.exit()
                    if event.key == pygame.K_RIGHT:

                        ship.movin_right = True

                    if event.key == pygame.K_LEFT:
                        ship.movin_left = True
                    if event.key == pygame.K_UP:

                        ship.movin_up = True
                    if event.key == pygame.K_i:
                        wea += 1
                        if wea == 2:
                            wea = 0

                    if event.key == pygame.K_DOWN:
                        ship.movin_down = True
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        ship.movin_right = False
                    if event.key == pygame.K_LEFT:
                        ship.movin_left = False
                    if event.key == pygame.K_UP:

                        ship.movin_up = False

                    if event.key == pygame.K_2:
                        ship.image = pygame.image.load(random.choice(images))
                    if event.key == pygame.K_DOWN:
                        ship.movin_down = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = pygame.mouse.get_pos()
                    if alien.rect.collidepoint(x, y):
                        ch -= 5
                    if alien2.rect.collidepoint(x, y):
                        ch2 -= 5

            isstickbut = joycon.stick_r_btn
            isstickmove = joycon.stick_r
            if isstickmove[1] > 2000:

                ship.rect.x += 3
                #('up')
            elif isstickmove[1] < 1000:
                #ship.y += 3
                #('down')
                ship.rect.x -= 3

            elif isstickmove[0] > 3000:
                #ship.x += 3
                #('r')
                ship.rect.y += 3
            elif isstickmove[0] < 1000:
                #ship.x -= 3
                #('l')
                ship.rect.y -= 3

            isstickbut = joycon2.stick_l_btn
            isstickmove = joycon2.stick_l

            if isstickmove[1] > 3000:
                print(isstickmove)
                ship2.rect.x -= 3
                #('up')
            elif isstickmove[1] < 2000:
                #ship.y += 3
                #('down')
                ship2.rect.x += 3

            elif isstickmove[0] > 3000:
                #ship.x += 3
                #('r')
                ship2.rect.y -= 3
            elif isstickmove[0] < 1500:
                #ship.x -= 3
                #('l')
                ship2.rect.y += 3

            for event_type, status in joycon.events():
                if status == 1:
                    if event_type == 'x':
                        bul = Bullet(ai_settings, screen, ship, alien, bullets)
                        bullets.add(bul)
                    if event_type == 'b':
                        bul = Bomb(ai_settings, screen, ship, alien, bullets)
                        bullets.add(bul)
                    if event_type == 'a':
                        bul = Bullet(ai_settings, screen, ship, alien, bullets)
                        bullets.add(bul)
                        pygame.time.wait(10)
                        bul = Bullet(ai_settings, screen, ship, alien, bullets)
                        bullets.add(bul)
                        pygame.time.wait(10)

                        bul = Bullet(ai_settings, screen, ship, alien, bullets)
                        pygame.time.wait(10)
                        bullets.add(bul)
            for event_type, status in joycon2.events():
                if status == 1:
                    if event_type == 'down':
                        bul = Bullet(ai_settings, screen, ship2, alien,
                                     bullets)
                        bullets.add(bul)
                    if event_type == 'up':
                        bul = Bomb(ai_settings, screen, ship2, alien, bullets)
                        bullets.add(bul)

#             isstickmove=joycon.stick_l
#             if isstickmove[1] > 3000:

#                 ship2.rect.x += 3
#                 #('up')
#             elif isstickmove[1] < 1000:
#                 #ship.y += 3
#                 #('down')
#                 ship2.rect.x -= 3

#             elif isstickmove[0] > 3000:
#                 #ship.x += 3
#                 #('r')
#                 ship2.rect.y += 3
#             elif isstickmove[0] < 1000:
#                 #ship.x -= 3
#                 #('l')
#                 ship2.rect.y -= 3
# #276
#             #ship.update()

#
#if alien.tu == 3:

            bullets.update(bullets, aliens)

            ##('you lose')
            #break
            ship.blitme()
            ship2.blitme()
            alien.blitme()
            for bullet in bullets.copy():
                if bullet.rect.bottom <= 0:
                    bullets.remove(bullet)

            screen.fill(ai_settings.bg_color)

            for bullet in bullets.sprites():

                bullet.draw_bullet()

                first = randint(0, 200)
                second = randint(0, 200)
                three = randint(0, 200)
                ai_settings.bullet_color = (first, second, three)
            bullets.update(bullets, aliens)
            if pygame.sprite.spritecollideany(ship, alienbullets):
                #('you lose')
                sys.exit()
            ert = randint(-10, 90)
            # if ert == 0:
            #     alienbul = alienBullet(ai_settings,screen,alien)
            #     alienbullets.add(alienbul)

            for bullet in bullets.copy():
                if bullet.rect.bottom <= 0:
                    alienbullets.remove(bullet)
            for bullet in bullets2.copy():
                if bullet.rect.x == bullet.mx and bullet.rect.y == bullet.my:
                    bullets.remove(bullet)
                    bullets2.remove(bullet)
            screen.fill(ai_settings.bg_color)

            for bullet in bullets.sprites():

                bullet.draw_bullet()

                first = randint(0, 200)
                second = randint(0, 200)
                three = randint(0, 200)
                ai_settings.bullet_color = (first, second, three)
            if pygame.sprite.spritecollideany(alien, bullets):
                ch -= 10
                bullets.remove(bullet)
                #                #(ch)
                if ch <= 0:
                    aliens.remove(alien)
                    #('you win')
                if len(aliens) <= 0:
                    break
            if pygame.sprite.spritecollideany(alien2, bullets):
                ch2 -= 10
                bullets.remove(bullet)
                #                #(ch)
                if ch2 <= 0:
                    aliens.remove(alien2)
                    #('you win')

                if len(aliens) <= 0:
                    break

            if pygame.sprite.spritecollideany(ship, aliens):
                brek = 1
                #('lose')
                sys.exit()
            if pygame.sprite.spritecollideany(ship2, aliens):
                brek = 1
                #('lose')
                sys.exit()
            collisions = pygame.sprite.groupcollide(bullets, aliens, True,
                                                    False)
            #            collisions = pygame.sprite.groupcollide(bullets,alienbullets,True,True)

            #           #(len(alienbullets))
            ship.blitme()
            ship2.blitme()
            alien.blitme()
            # aliens.update()
            ##############################################################

            # x-coordinate
            # if alien.rect.x>=1400 and right_x_border==False:
            #     right_x_border=True
            # if alien.rect.x<=0 and right_x_border==True:
            #     right_x_border=False

            # if right_x_border==False:
            #    step_x=1
            # if right_x_border==True:
            #    step_x=-1

            # # y-coordinate
            # if alien.rect.y>=1000 and down_y_border==False:
            #     down_y_border=True
            # if alien.rect.y<=0 and down_y_border==True:
            #     down_y_border=False

            # if down_y_border==False:
            #    step_y=1
            # if down_y_border==True:
            #    step_y=-1

            # # alien move to coordinates x,y
            # alien.rect.x=alien.rect.x+step_x
            # alien.rect.y=alien.rect.y+step_y
            if alien.rect.x < ship.rect.x:
                alien.rect.x += 1
            if alien.rect.x > ship.rect.x:
                alien.rect.x -= 1
            if alien.rect.y < ship.rect.y:
                alien.rect.y += 1
            if alien.rect.y > ship.rect.y:
                alien.rect.y -= 1

            if alien2.rect.x < ship2.rect.x:
                alien2.rect.x += 1
            if alien2.rect.x > ship2.rect.x:
                alien2.rect.x -= 1
            if alien2.rect.y < ship2.rect.y:
                alien2.rect.y += 1
            if alien2.rect.y > ship2.rect.y:
                alien2.rect.y -= 1

##############################################################
            aliens.draw(screen)

            alienbullets.update(bullets, aliens)
            print(ch)
            print(ch2)

            pygame.display.flip()
Exemplo n.º 30
0
def run_game():
    # Initialize game and create a screen object.
    frequency = 42050
    pygame.mixer.init(frequency)
    pygame.mixer.music.load('audio/OST.mp3')
    pygame.mixer.music.play(-1)
    pygame.init()
    ufo_effect = pygame.mixer.Sound('audio/ufo.wav')
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")
    highscore_button = Button2(ai_settings, screen, "High Score")
    back_button = Button2(ai_settings, screen, "Back")

    # Make a ship.
    ship = Ship(ai_settings, screen)

    # Make a ufo
    ufo = Ufo(ai_settings, screen)

    # Make a group to store bullets in.
    bullets = Group()
    bullets2 = Group()

    # Make an alien
    aliens = Group()

    # Make barriers
    barriers = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Create a group of barriers
    gf.create_barriers(ai_settings, screen, ship, barriers)

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    highScoreFile = open("highscore.txt", "r")
    stats.high_score = int(highScoreFile.readline())
    highScoreFile.close()
    sb = Scoreboard(ai_settings, screen, stats)
    spaceText = Text(ai_settings, screen, "SPACE", 200, 40,
                     ai_settings.screen_width / 2 - 50, 40, (255, 255, 255))
    invadersText = Text(ai_settings, screen, "INVADERS", 200, 40,
                        ai_settings.screen_width / 2 - 75, 80, (0, 255, 0))
    pinkyPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 190,
                           pygame.image.load('images/pinky_2.png'))
    pinkyText = Text(ai_settings, screen, "= 10 PTS     PINKY", 200, 40,
                     ai_settings.screen_width / 2, 190, (255, 255, 255))
    blueyPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 240,
                           pygame.image.load('images/bluey_2.png'))
    blueyText = Text(ai_settings, screen, "= 20 PTS     BLUEY", 200, 40,
                     ai_settings.screen_width / 2, 240, (255, 255, 255))
    greenyPicture = Picture(ai_settings, screen,
                            ai_settings.screen_width / 2 - 75, 290,
                            pygame.image.load('images/greeny_2.png'))
    greenyText = Text(ai_settings, screen, "= 40 PTS     GREENY", 200, 40,
                      ai_settings.screen_width / 2, 290, (255, 255, 255))
    oscarPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 340,
                           pygame.image.load('images/oscar.png'))
    oscarText = Text(ai_settings, screen, "= ???           OSCAR", 200, 40,
                     ai_settings.screen_width / 2, 340, (255, 255, 255))
    list = None
    animation_clock = ai_settings.animation_clock

    while True:
        highscoreText = Text(ai_settings, screen,
                             "HIGH SCORE: " + str(stats.high_score), 200, 40,
                             ai_settings.screen_width / 2 - 100, 40,
                             (255, 255, 255))
        menu_loop = True
        pygame.mixer.quit()
        pygame.mixer.init(frequency)
        pygame.mixer.music.load('audio/OST.mp3')
        pygame.mixer.music.play(-1)
        pygame

        while menu_loop:
            menu_loop = gf.check_menu_events(ai_settings, screen, stats, sb,
                                             play_button, ship, aliens,
                                             bullets, highscore_button,
                                             back_button, highscoreText,
                                             bullets2)
            gf.update_menu_screen(ai_settings, screen, play_button,
                                  highscore_button, spaceText, invadersText,
                                  pinkyPicture, blueyPicture, greenyPicture,
                                  oscarPicture, pinkyText, blueyText,
                                  greenyText, oscarText)

        # Start the main loop for the game.
        while stats.game_active:
            gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                            aliens, bullets)
            if stats.game_active:
                ship.update()
                gf.update_barriers(ai_settings, screen, barriers, aliens, ship)
                temp = gf.update_bullets(ai_settings, screen, stats, sb, ship,
                                         aliens, bullets, bullets2, ufo,
                                         barriers)
                if temp is not None:
                    list = temp
                gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                                 bullets, bullets2, ufo)

            animation_clock = gf.update_screen(ai_settings, screen, stats, sb,
                                               ship, aliens, bullets,
                                               play_button, bullets2, ufo,
                                               barriers, list, animation_clock)