示例#1
0
    def __init__(self, row, col, sizeRow, sizeCol, health, sheild, imageName):
        super(TerranBuilding, self).__init__(row, col, sizeRow, sizeCol, health, 0, 0, 0, imageName)
        self.buildRound = 3
        self.Avatar = load.load_avatar('Terran/Advisor.gif')
        self.idleSounds = [load.load_sound('Terran/Bldg/TCsSca00.wav')]
        self.deathSound = [load.load_sound('Misc/explo5.wav')]

        TerranBuilding.terranBuildings.append(self)
    def __init__(self, row, col, sizeRow, sizeCol, health, sheild, imageName):
        super(ProtossBuilding, self).__init__(row, col, sizeRow, sizeCol, health, sheild, 0, 5, imageName)
        self.buildRound = 3
        self.Avatar = load.load_avatar('Protoss/Advisor.gif')
        self.idleSounds = [load.load_sound('Protoss/Bldg/pneWht00.wav')]
        self.deathSound = [load.load_sound('Misc/explo4.wav')]

        ProtossBuilding.protossBuildings.append(self)
示例#3
0
    def __init__(self, race, startRow, startCol,index):
        self.index = index
        self.resources = 50
        self.winSound = load.load_sound('Misc/YouWin.wav')
        if race == 'Protoss':
            nexus = ProtossBuildings.Nexus(startRow,startCol)
            Building.building.addTofinishedBuildings(nexus)
            ProtossUnit.Probe(startRow,startCol-1)
            ProtossUnit.Probe(startRow-1,startCol-1)
            ProtossUnit.Probe(startRow+1,startCol-1)
            ProtossUnit.Probe(startRow+2,startCol-1)
            ProtossUnit.Probe(startRow+3,startCol-1)
            self.xPos = 0
            self.yPos = 0
            self.Units = ProtossUnit.ProtossUnit.ProtossUnits
            self.Buildings = ProtossBuildings.ProtossBuilding.protossBuildings
            self.UntCls = ProtossUnit.ProtossUnit
            self.BldCls = ProtossBuildings.ProtossBuilding

            self.NoMineralSound = load.load_sound('Protoss/PAdErr00.wav')
            self.NoMoreSupplySound = load.load_sound('Protoss/PAdErr02.wav')

            MenuFile = 'Other/Menu/Protoss Menu.png'
            self.MenuImage = load.load_image(MenuFile)
        if race == 'Terran':
            cc = TerranBuildings.CommandCenter(startRow,startCol)
            Building.building.addTofinishedBuildings(cc)
            TerranUnit.SCV(startRow,startCol-1)
            TerranUnit.SCV(startRow-1,startCol-1)
            TerranUnit.SCV(startRow+1,startCol-1)
            TerranUnit.SCV(startRow+2,startCol-1)
            TerranUnit.SCV(startRow+3,startCol-1)
            self.xPos = 0
            self.yPos = 0
            self.Units = TerranUnit.TerranUnit.TerranUnits
            self.Buildings = TerranBuildings.TerranBuilding.terranBuildings

            self.UntCls = TerranUnit.TerranUnit
            self.BldCls = TerranBuildings.TerranBuilding

            self.NoMineralSound = load.load_sound('Terran/tadErr00.wav')
            self.NoMoreSupplySound = load.load_sound('Terran/tadErr02.wav')

            MenuFile = 'Other/Menu/Terran Menu.png'
            self.MenuImage = load.load_image(MenuFile)

        self.updateCurrentPopulation()
        self.updateCurrentPopulationAvaliable()
示例#4
0
文件: menu.py 项目: Babulu/Kirby
 def __init__(self):
     self.menu1 = load.load_image("menu1.png")
     self.menu2 = load.load_image("menu2.png")
     self.menu3 = load.load_image("menu3.png")
     self.menu = [self.menu1,self.menu2,self.menu3]
     self.instruction = load.load_image("instruction.png")
     self.index = 0
     self.start = False
     self.info = False
     self.menuSound = load.load_sound("menuDing.WAV")
     self.enter = False
示例#5
0
文件: mixer.py 项目: gshopov/Pyruto
    def __init__(self, character):
        """Initialize pygame.mixer if it is not already and load all sound
        effects of the character.

        """
        if pygame.mixer.get_init() is None:
            pygame.mixer.init()

        self.sounds = {key: load_sound(value) for key in
                       get_all_sounds(character)
                       for value in glob.glob("assets/characters/" +
                                              character + "/sound_effects/"
                                              + key + "/*")}
示例#6
0
    def __init__(self):
        """Initialize all attributes, load music and scale every sprite in
        the group if the current resolution is lower than the default one.

        """
        SpriteGroup.__init__(self)

        self.background = Background("assets/backgrounds/character_menu.jpg")
        self.icon_matrix = IconMatrix(self._calculate_icon_space())
        self.icon_matrix.position = Vec2D(((DEFAULT_SCREEN_SIZE[0] -
                                            ICON_SIZE[0] *
                                            self.icon_matrix.size[1]) / 2,  0))

        self._init_players_position()

        self.p1_repr = Representation(self.get_p1_character(), "RIGHT")
        self.p2_repr = Representation(self.get_p2_character(), "LEFT")

        self.add(self.background, self.p1_repr, self.p2_repr, self.icon_matrix)

        self.music = load_sound("assets/sound/character_menu/" +
                                "01_Shippuuden.ogg")
示例#7
0
def main():
    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

# Create the background which will scroll and loop over a set of different
# size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))

# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

# Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()                                       #sprites의 ship 클래스를 넣는다
    initialAlienTypes = (Siney,Oneeye, Spikey,Eye)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship,))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [font.render("NAME", 1, RED),
                      font.render("SCORE", 1, RED),
                      font.render("ACCURACY", 1, RED)]
    highScorePos = [highScoreTexts[0].get_rect(
                      topleft=screen.get_rect().inflate(-100, -100).topleft),
                    highScoreTexts[1].get_rect(
                      midtop=screen.get_rect().inflate(-100, -100).midtop),
                    highScoreTexts[2].get_rect(
                      topright=screen.get_rect().inflate(-100, -100).topright)]
    for hs in hiScores:
        highScoreTexts.extend([font.render(str(hs[x]), 1, BLUE)
                               for x in range(3)])
        highScorePos.extend([highScoreTexts[x].get_rect(
            topleft=highScorePos[x].bottomleft) for x in range(-3, 0)])

    
    main_dir = os.path.split(os.path.abspath(__file__))[0]
    data_dir = os.path.join(main_dir, 'data')
    fullname1 = os.path.join(data_dir, 'ship.png')
    fullname2 = os.path.join(data_dir, 'ship2.png')
    fullname3 = os.path.join(data_dir, 'ship3.png')
    fullname4 = os.path.join(data_dir, 'ship4.png')
    image1 = pygame.image.load(fullname1)
    image2 = pygame.image.load(fullname2)
    image3 = pygame.image.load(fullname3)
    image4 = pygame.image.load(fullname4)

    #imageload = [font.render("FIRST SELECT SHIP",1, RED),
     #            font.render("SECOND SELECT SHIP",1,RED),
     #            font.render("THIRD SELECT SHIP",1,RED)
     #           ]
    #imagePos = [(imageload[0].get_rect(topleft=screen.get_rect().inflate(-100, -100).midbottom)),
    #            (imageload[1].get_rect(topleft=screen.get_rect().inflate(-100, -100).midtop)),
     #           (imageload[2].get_rect(topleft=screen.get_rect().inflate(-100, -100).topright))
     #           ]

   
    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop
    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)


    
    title1, titleRect1 = load_image('title.png')
    titleRect1.midtop = screen.get_rect().inflate(0, -200).midtop
    image1 = pygame.image.load(fullname1)
    startPos1 = image1.get_rect(midtop=titleRect1.inflate(0, 100).midbottom)
    image2 = pygame.image.load(fullname2)
    hiScorePos1 = image2.get_rect(topleft=startPos1.bottomleft)
    image3 = pygame.image.load(fullname3)
    fxPos1 = image3.get_rect(topleft=hiScorePos1.bottomleft)
    image4 = pygame.image.load(fullname4)
    fxOnPos1 = image4.get_rect(topleft=fxPos1.bottomleft)

    selectText1 = font.render('*', 1, BLUE)
    selectPos1 = selectText.get_rect(topright=startPos1.topleft)
    menuDict1 = {1: startPos1, 2: hiScorePos1, 3: fxPos1, 4: fxOnPos1}
    selection1 = 1

    
    is_end = True
    while inMenu:
        clock.tick(clockTime)
            

        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    while is_end:
                        clock.tick(clockTime)
                        screen.blit(
                            background, (0, 0), area=pygame.Rect(
                                0, backgroundLoc, 500, 500))
                        backgroundLoc -= speed
                        if backgroundLoc - speed <= speed:
                            backgroundLoc = 1500

                        for event1 in pygame.event.get():
                            if (event1.type == pygame.QUIT):
                                return
                            elif(event1.type == pygame.KEYDOWN
                                 and event1.key == pygame.K_RETURN):
                                if selection1 ==1:
                                    abcd = 'ship.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==2:
                                    abcd = 'ship2.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==3:
                                    abcd = 'ship3.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==4:
                                    abcd = 'ship4.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_w
                                  and selection1 > 1):
                                selection1 -= 1
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_s
                                  and selection1 < len(menuDict1)):
                                selection1 += 1
                        selectPos1 = selectText1.get_rect(topright=menuDict1[selection1].topleft)
                        textOverlays1 = zip([image1, image2, image3, image4,selectText1],
                                       [startPos1, hiScorePos1, fxPos1, fxOnPos1,selectPos1])
                        screen.blit(title, titleRect)
                        for txt1, pos1 in textOverlays1:
                            screen.blit(txt1, pos1)
                        pygame.display.flip()
                               
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
                elif selection ==6:
                    return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_w
                  and selection > 1
                  and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_s
                  and selection < len(menuDict)
                  and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)
        

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
       
        else:
            textOverlays = zip([startText, hiScoreText, fxText,
                                musicText, quitText, selectText,
                                fxOnText if soundFX else fxOffText,
                                musicOnText if music else musicOffText],
                               [startPos, hiScorePos, fxPos,
                                musicPos, quitPos, selectPos,
                                fxOnPos if soundFX else fxOffPos,
                                musicOnPos if music else musicOffPos])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

            

       

    while ship.alive:
        clock.tick(clockTime)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed
                ship.vert += direction[event.key][1] * speed
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed
                ship.vert -= direction[event.key][1] * speed
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
        # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(
                        missile, alien) and alien in Alien.active:
                    alien.table()
                    missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave),
                               1, BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)

        text = [waveText, leftText, scoreText, bombText]
        textposition = [wavePos, leftPos, scorePos, bombPos]

    # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render(
                    'Wave ' + str(wave + 1) + ' in', 1, BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                    Alien.pool.add([F() for _ in range(5)])#새로운 외계인 F 1페이즈 출현
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                    Alien.pool.add([Oak() for _ in range(5)])#오크 2페이즈 출현
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

    # Update and draw all sprites and text
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or not isHiScore
                and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE
                  and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip([hiScoreText, scoreText,
                               enterNameText, nameText],
                              [hiScorePos, scorePos,
                               enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()
示例#8
0
文件: main.py 项目: Babulu/Kirby
pygame.display.set_caption("Kirby")
screen = pygame.display.get_surface()

# Create instances
kirby = kirby.kirby()
hand = handCursor.Hand()
clock = pygame.time.Clock()
spriteGroup = spriteGroup.spriteGroup()
landscape = landscape.landscape()
menu = menu.menu()
subscreen = subscreen.subscreen()

# Use Struct to store globals
class Struct: pass
data = Struct()
data.menuMusic = load.load_sound("menu.wav")
data.gameMusic = load.load_sound("game.wav")
data.event = pygame.event.poll()
data.key = pygame.key.get_pressed()
data.mouse_pos = pygame.mouse.get_pos()
data.mouseEvent = pygame.mouse.get_pressed()

# Add Pikey
def addPikey():
    if kirby.frame_w % 173 == 50:
        pikey = enemies.pikey(600,336)
        data.pikeyList.append(pikey)
    for p in data.pikeyList:
        p.movement(screen,spriteGroup,hand,data.mouseEvent,data.key)
        if p.x < -26:
            data.pikeyList.remove(p)
示例#9
0
def main():

    #mindwaveDataPointReader = MindwaveDataPointReader()
    #mindwaveDataPointReader.start()
    #if not (mindwaveDataPointReader.isConnected()):
    #print((textwrap.dedent("""\
    #Exiting because the program could not connect
    #to the Mindwave Mobile device.""").replace("\n", " ")))
    #sys.exit()

    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

    # Create the background which will scroll and loop over a set of different
    # size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))


# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()
    initialAlienTypes = (Siney, Spikey)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship, ))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [
        font.render("NAME", 1, RED),
        font.render("SCORE", 1, RED),
        font.render("ACCURACY", 1, RED)
    ]
    highScorePos = [
        highScoreTexts[0].get_rect(
            topleft=screen.get_rect().inflate(-100, -100).topleft),
        highScoreTexts[1].get_rect(
            midtop=screen.get_rect().inflate(-100, -100).midtop),
        highScoreTexts[2].get_rect(
            topright=screen.get_rect().inflate(-100, -100).topright)
    ]
    for hs in hiScores:
        highScoreTexts.extend(
            [font.render(str(hs[x]), 1, BLUE) for x in range(3)])
        highScorePos.extend([
            highScoreTexts[x].get_rect(topleft=highScorePos[x].bottomleft)
            for x in range(-3, 0)
        ])

    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop

    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)

    while inMenu:
        clock.tick(clockTime)

        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    inMenu = False
                    ship.initializeKeys()
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_w
                  and selection > 1 and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_s
                  and selection < len(menuDict) and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
        else:
            textOverlays = zip([
                startText, hiScoreText, fxText, musicText, quitText,
                selectText, fxOnText if soundFX else fxOffText,
                musicOnText if music else musicOffText
            ], [
                startPos, hiScorePos, fxPos, musicPos, quitPos, selectPos,
                fxOnPos if soundFX else fxOffPos,
                musicOnPos if music else musicOffPos
            ])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    medVal = 0
    attVal = 0
    while medVal == 0 and attVal == 0:
        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

    while ship.alive:
        clock.tick(clockTime)

        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed  #*medVal
                ship.vert += direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed  #*medVal
                ship.vert -= direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
    # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(missile,
                                              alien) and alien in Alien.active:
                    alien.table()

                    #Peiercing bullets
                    if medVal < 40:
                        missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave), 1,
                               BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)

        dataText = font.render("(A): " + str(attVal) + " (M): " + str(medVal),
                               1, RED)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)
        dataPos = dataText.get_rect(bottomright=screen.get_rect().bottomright)

        text = [waveText, leftText, scoreText, bombText, dataText]
        textposition = [wavePos, leftPos, scorePos, bombPos, dataPos]

        # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render('Wave ' + str(wave + 1) + ' in', 1,
                                           BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

        # Update and draw all sprites and text
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

        # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                    or not isHiScore and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip(
                [hiScoreText, scoreText, enterNameText, nameText],
                [hiScorePos, scorePos, enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()