加入Pygame中的敌人?

时间:2013-12-07 16:46:36

标签: python python-2.7 pygame

我正试图将从敌人死亡中随机丢弃添加到我在Python中制作的游戏,并想知道如何实现它。我想要添加的水滴是盾和健康,盾具有较低的掉落几率。 Drops的主要代码在这里:

import pygame

class HealthDrop(pygame.sprite.Sprite):

        def __init__(self, x, y):

                self.image = pygame.image.load('images/Sprites/health.png')

                self.rect = self.image.get_rect()
                self.rect.x = x
                self.rect.y = y

                self.on_ground = False
                self.gravity = 0.5

        def update(self):


        def render(self, surface):
                surface.blit(self.image, self.rect)

class ShieldDrop(pygame.sprite.Sprite):

        def __init__(self, x, y):

                self.image = pygame.image.load('images/Sprites/shield.png')

                self.rect = self.image.get_rect()
                self.rect.x = x
                self.rect.y = y

                self.on_ground = False
                self.gravity = 0.5

        def update(self):


        def render(self, surface):
                surface.blit(self.image, self.rect)

然后主文件的代码在这里:

import pygame, sys
import random
import pygame.mixer
import Funk
from time import sleep
from player import *
from zombie import *
from level import *
from bullet import *
from constants import *
from Drops import *
import menu as dm

class Game():

    def __init__(self):
        pygame.init()
        pygame.mixer.init()

        #pygame.mixer.music.load('sounds/menugame.ogg')
        #pygame.mixer.music.play(-1)

        # A few variables
        self.gravity = .50
        self.ground = pygame.Rect(0, 640, 1280, 80)
        self.red = (255, 0, 0)
        self.darkred = (200, 0, 0)
        self.darkblue = (0, 0, 200)
        self.darkgreen = (0, 200, 0)
        self.gameover = pygame.image.load('images/gameover.png')
        self.victory = pygame.image.load('images/victory.png')

        # Bullets
        self.bullets = []

        # Screen
        size = (1280, 720)
        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption('Moon Survival!')

        # Moon / Background
        self.moon = Background()
        self.text1 = pygame.image.load('images/TextSlides/Text1.jpg')
        self.text2 = pygame.image.load('images/TextSlides/Text2.jpg')

        # Zombies
        self.zombies = []
        for i in range(15):
            self.zombies.append( Zombie(random.randint(0,1280), random.randint(0,720)) )

        self.zombieskilled = 0

        # Player
        self.player = Player(25, 320, self.gravity)

        # Font for text
        self.font = pygame.font.SysFont(None, 72)

        # game over
        self.gameover_text = self.font.render("The Aliens Are Too Good", -1, (255, 0, 0))
        self.gameover_rect = self.gameover_text.get_rect(center=self.screen.get_rect().center)

        # game state
        self.game_state = STATE_INGAME

    def run(self):

        clock = pygame.time.Clock()

        # "state machine" 
        RUNNING   = True
        PAUSED    = False 
        GAME_OVER = False

        # Game loop
        while RUNNING:

            # (all) Events
            if self.game_state == STATE_INGAME:

                for event in pygame.event.get():

                    if event.type == pygame.QUIT:
                        RUNNING = False

                    elif event.type == pygame.KEYDOWN:

                        if event.key == pygame.K_s:
                            self.bullets.append(Bullet(self.player.rect.x + 30, self.player.rect.y + 30, self.player.direction))

                        if event.key == pygame.K_ESCAPE:
                            RUNNING = False

                        elif event.key == pygame.K_p:
                            # set state to paused
                            self.game_state = STATE_PAUSED

                    # Player/Zomies events  
                    self.player.handle_events(event)

                # (all) Movements / Updates

                self.player_move()
                self.player.update()

                for z in self.zombies:
                    self.zombie_move(z)       
                    z.update(self.screen.get_rect())

                for b in self.bullets:
                    b.update()
                    for tile in self.moon.get_surrounding_blocks(b):
                        if tile is not None:
                            if pygame.sprite.collide_rect(b, tile):
                                # Destroy block
                                x = tile.rect.x / tile.rect.width
                                y = tile.rect.y / tile.rect.height
                                self.moon.levelStructure[x][y] = None
                                self.bullets.remove(b)

                # (all) Display updating

                self.moon.render(self.screen)

                for z in self.zombies:
                    z.render(self.screen)

                for b in self.bullets:
                    b.render(self.screen)

                self.player.render(self.screen)

                Funk.text_to_screen(self.screen, 'Level 1', 5, 675)
                Funk.text_to_screen(self.screen, 'Health: {0}'.format(self.player.health), 5, 0)
                Funk.text_to_screen(self.screen, 'Score: {0}'.format(self.player.score), 400, 0)
                Funk.text_to_screen(self.screen, 'Time: {0}'.format(self.player.alivetime), 750, 0)
                Funk.text_to_screen(self.screen, 'Kills: {0}'.format(self.zombieskilled), 5, 50)
                Funk.text_to_screen(self.screen, 'Lives: {0}'.format(self.player.lives), 300, 50)

            elif self.game_state == STATE_PAUSED:
                # (all) Display updating

                if self.game_state == STATE_INGAME:
                    if event.type == pygame.QUIT:
                        RUNNING = False

                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            RUNNING = False

                choose = dm.dumbmenu(self.screen, [
                            'Resume Game',

                            'Menu',

                            'Quit Game'], 200, 200,'orecrusherexpanded',100,0.75,self.darkred,self.red)

                if choose == 0:
                    print "You choose 'Start Game'."
                    # set state to ingame
                    self.game_state = STATE_INGAME
                elif choose == 1:
                    print "You choose 'Controls'."
                if choose == 2:
                    print "You choose 'Quit Game'."
                    pygame.quit()
                    sys.exit()

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


                self.moon.render(self.screen)

                for z in self.zombies:
                    z.render(self.screen)

                for b in self.bullets:
                    b.render(self.screen)

                self.player.render(self.screen)

                Funk.text_to_screen(self.screen, 'Level 1', 5, 675)
                Funk.text_to_screen(self.screen, 'Health: {0}'.format(self.player.health), 5, 0)
                Funk.text_to_screen(self.screen, 'Score: {0}'.format(self.player.score), 400, 0)
                Funk.text_to_screen(self.screen, 'Time: {0}'.format(self.player.alivetime), 750, 0)
                Funk.text_to_screen(self.screen, 'Kills: {0}'.format(self.zombieskilled), 850, 0)

            elif self.game_state == STATE_GAMEOVER:
                self.screen.blit(self.gameover, (0, 0))
                pygame.display.update()
                choose = dm.dumbmenu(self.screen, [
                            'New Game',
                            '  Menu  ',
                            'Quit Game'], 200, 300,'orecrusherexpanded',100,0.75,self.darkred,self.red)

                if choose == 0:
                    print "You choose 'Start Game'."
                    # set state to ingame
                    self.game_state = STATE_INGAME

                    execfile('MoonSurvival.py')
                if choose == 1:
                    print "You choose 'Start Game'."
                    execfile('run_game.py')

                if choose == 2:
                    print "You choose 'Start Game'."
                    pygame.quit()
                    sys.exit()

            pygame.display.update()

            # FTP

            clock.tick(100)

        # --- the end ---
        pygame.quit()

    def player_move(self):
        # add gravity
        self.player.do_jump()

        # simulate gravity
        self.player.on_ground = False
        if not self.player.on_ground and not self.player.jumping:
            self.player.velY = 4

        # Health
        for zombie in self.zombies:
            if pygame.sprite.collide_rect(self.player, zombie):
                self.player.health -= 5

                # check if we die
                if self.player.health <= 0:
                    self.player.lives -= 1
                    self.player.rect.x = 320
                    self.player.rect.y = 320
                    self.player.health += 200
                if self.player.lives <= 0:
                    sleep(2)
                    self.game_state = STATE_GAMEOVER

        # move player and check for collision at the same time
        self.player.rect.x += self.player.velX
        self.check_collision(self.player, self.player.velX, 0)
        self.player.rect.y += self.player.velY
        self.check_collision(self.player, 0, self.player.velY)

    def zombie_move(self, zombie_sprite):
        # add gravity
        zombie_sprite.do_jump()

        # simualte gravity
        zombie_sprite.on_ground = False
        if not zombie_sprite.on_ground and not zombie_sprite.jumping:
            zombie_sprite.velY = 4

        # Zombie damage
        for zombie in self.zombies:
            for b in self.bullets:
                if pygame.sprite.collide_rect(b, zombie):
                    #The same bullet cannot be used to kill
                    #multiple zombies and as the bullet was 
                    #no longer in Bullet.List error was raised
                    zombie.health -= 10                
                    self.bullets.remove(b)
                    if zombie.health <= 0:
                        self.zombieskilled += 1
                        self.player.score += 20
                        self.zombies.remove(zombie)
                    break

        # move zombie and check for collision
        zombie_sprite.rect.x += zombie_sprite.velX
        self.check_collision(zombie_sprite, zombie_sprite.velX, 0)
        zombie_sprite.rect.y += zombie_sprite.velY
        self.check_collision(zombie_sprite, 0, zombie_sprite.velY)

    def check_collision(self, sprite, x_vel, y_vel):
        # for every tile in Background.levelStructure, check for collision
        for block in self.moon.get_surrounding_blocks(sprite):
            if block is not None:
                if pygame.sprite.collide_rect(sprite, block):
                    # we've collided! now we must move the collided sprite a step back
                    if x_vel < 0:
                        sprite.rect.x = block.rect.x + block.rect.w

                        if type(sprite) is Zombie:
                            # the sprite is a zombie, let's make it jump
                            if not sprite.jumping:
                                sprite.jumping = True
                                sprite.on_ground = False

                    if x_vel > 0:
                        sprite.rect.x = block.rect.x - sprite.rect.w

                        if type(sprite) is Zombie:
                            # the sprite is a zombie, let's make it jump
                            if not sprite.jumping:
                                sprite.jumping = True
                                sprite.on_ground = False

                    if y_vel < 0:
                        sprite.rect.y = block.rect.y + block.rect.h

                    if y_vel > 0 and not sprite.on_ground:
                        sprite.on_ground = True
                        sprite.rect.y = block.rect.y - sprite.rect.h

#---------------------------------------------------------------------

Game().run()

1 个答案:

答案 0 :(得分:1)

你需要编辑它:

def zombie_move(self, zombie_sprite):
    for zombie in self.zombies:
        for b in self.bullets:
            if pygame.sprite.collide_rect(b, zombie):
                zombie.health -= 10                
                self.bullets.remove(b)
                if zombie.health <= 0:
                    self.zombieskilled += 1
                    self.player.score += 20

                    #You need some code here (before removing the zombie)

                    self.zombies.remove(zombie)
                break

对不起,我忘记了如何在Python中做到这一点,但逻辑是这样的:代替代码中的注释,添加类似HealthDrop.append(x, y)ShieldDrop.append(x, y)的内容,其中x和y应该是僵尸的价值(这就是为什么你应该在移除僵尸之前做到这一点)。

如果您想要随机添加import random,请执行以下操作:

percentage = random.randint(1, 100)

if (percentage >= 1) and (percentage < 10)
    healthDrop.append(zombie.x, zombie.y)
else
if (percentage >= 10) and (percentage < 20)
    shieldDrop.append(zombie.x, zombie.y)

在这个例子中,我为每个“item”设置10%放弃(它们不能同时掉落),它将一个数字从1到100随机化,如果它是1到9的数字,它的healthDrop,如果它是一个数字从10到19它的shieldDrop,随意尝试百分比使你的游戏平衡

另外不要忘记添加碰撞(我看到你已经有一些碰撞代码所以我猜你知道怎么做)。其余代码应该很容易做到(比如提高健康等等。

我很抱歉我不记得python真的很好,但是你可以使用它们类似于子弹类,我希望你有这个想法,如果有什么麻烦你请告诉我,我会帮助更多:)