2016-01-22 57 views
1
import pygame 
import os,sys 
import random 
import math 

img_path = os.path.join("punch.png") 
img_blob = os.path.join("blob.png") 

class Enemy(object): 
    def __init__(self,x,y): 
     super(Enemy,self).__init__() 
     self.image = pygame.Surface([160,160]) 
     self.image.set_colorkey(black) 
     self.image.blit(pygame.image.load(img_blob),(0,0)) 
     self.rect = self.image.get_rect() 
     self.rect.x = x 
     self.rect.y = y 
     self.speed = 2 
    def move_towards_player(self,character): 
     dx,dy = character.rect.x - self.rect.x,character.rect.y - self.rect.y 
     dist = math.hypot(dx,dy) 
     dx,dy = dx/dist,dy/dist 
     self.rect.x += dx * self.speed 
     self.rect.y += dy * self.speed 
    def draw(self,surface): 

     surface.blit(self.image,(self.rect.x,self.rect.y)) 
class character(pygame.sprite.Sprite): 

    def __init__(self, x = 275, y = 250): 

     super(character,self).__init__() 
     self.image = pygame.Surface([160,160]) 
     self.image.set_colorkey(black) 
     self.image.blit(pygame.image.load(img_path),(0,0)) 
     self.rect = self.image.get_rect() 
     self.rect.x = x 

     self.rect.y = y 



    def movement(self): 

     key = pygame.key.get_pressed() 

     dist = 10 

     if key[pygame.K_w]: 

      self.rect.y -= dist 

     elif key[pygame.K_s]: 

      self.rect.y += dist 

     if key[pygame.K_a]: 

      self.rect.x -= dist 

     elif key[pygame.K_d]: 

      self.rect.x += dist 


     if self.rect.x > 1110: 

      self.rect.x = 1110 

     if self.rect.y < 20: 

      self.rect.y = 20 

     elif self.rect.y > 710: 

      self.rect.y = 710 
     if self.rect.x <20: 
      self.rect.x = 20 
     elif self.rect.x == 1110 and self.rect.y > 300 and self.rect.y < 400: 
      self.rect.x = 25 
     if self.rect.y == 20 and self.rect.x >500 and self.rect.x < 600: 
      self.rect.y = 715 
     elif self.rect.x == 20 and self.rect.y > 300 and self.rect.y < 400: 
      self.rect.x = 1090 
     if self.rect.y == 710 and self.rect.x >500 and self.rect.x < 600: 
      self.rect.y = 25 

# top of left and right doors are y = 220, bottom of left and right doors are y = 240 # right side of top and bottom doors are x = 285, left of top and bottom doors are x = 260 
def collide(self,enemy,enemy_list): 
    if self.rect.colliderect(enemy.rect): 
     enemy_list.remove(enemy) 

def draw(self,surface): 

    surface.blit(self.image,(self.rect.x,self.rect.y)) 






pygame.init()        # Pygame is initialised (starts running) 

players = pygame.sprite.Group() 

screen = pygame.display.set_mode([1250,850]) # Set the width and height of the screen [width,height] 

pygame.display.set_caption("My Game")  # Name your window 

background_image = pygame.image.load("untilted.png") 


done = False        # Loop until the user clicks the close button. 

clock = pygame.time.Clock()     # Used to manage how fast the screen updates 

black = ( 0, 0, 0)     # Define some colors using rgb values. These can be 

white = (255, 255, 255)     # used throughout the game instead of using rgb values. 



# Define additional Functions and Procedures here 
score = 0 
bird = character() 
blob = Enemy(random.randint(10,700),random.randint(10,400)) 
enemies = [blob] 

# -------- Main Program Loop ----------- 

while done == False: 



    for event in pygame.event.get():  # Check for an event (mouse click, key press) 

     if event.type == pygame.QUIT:  # If user clicked close window 

      done = True      # Flag that we are done so we exit this loop 

# Update sprites here 
    for blob in enemies: 
     blob.move_towards_player(bird) 
     bird.collide(blob,enemies) 
     blob.draw(screen) 
    bird.movement() 

    screen.blit(background_image,[0,0]) 

    bird.draw(screen) 
    blob.draw(screen) 



    pygame.display.update()     # Go ahead and update the screen with what we've drawn. 

    clock.tick(20)      # Limit to 20 frames per second 
    score += 1 
pygame.quit()        # Close the window and quit. 

當我運行的代碼,blob(敵人)不會產卵,但當我在敵人取出敵人,這是假設是碰撞,blob產生,並遵循。我已經嘗試了很多碰撞的東西,但這是我第一次在pygame中創建一個遊戲,所以我必須查看所有東西。我想添加碰撞,但它不工作

回答

0

我想你的問題是,有時你的敵人會直接產生在玩家旁邊,所以碰撞會立即發生。我不知道你使用的圖像是怎麼樣的,但是要確保它們沒有太大的空間,因爲你的碰撞不是完美的像素,而是使用圖像的整個大小/矩形。

否則,你的代碼應該工作得很好,但你仍然可以改進一點。例如,因爲您已經爲character使用了Sprite類,您還可以使用Group類來使代碼更簡單一些(繪圖/移動/碰撞檢測)。

下面是它怎麼可能是這樣的:

import pygame 
import os,sys 
import random 
import math 

img_path = os.path.join("punch.png") 
img_blob = os.path.join("blob.png") 

class Actor(pygame.sprite.Sprite): 

    def __init__(self, x, y): 
     super(Actor,self).__init__() 
     self.image = pygame.Surface([160,160]) 
     self.image.set_colorkey(black) 
     self.image.blit(pygame.image.load(img_path),(0,0)) 
     self.rect = self.image.get_rect() 
     self.rect.x = x 
     self.rect.y = y 
     self.speed = 2 

class Enemy(Actor): 

    def __init__(self, x, y): 
     super(Enemy, self).__init__(x, y) 
     self.target = None 

    def update(self, enemies): 
     if self.target: 
      dx,dy = self.target.rect.x - self.rect.x, self.target.rect.y - self.rect.y 
      dist = math.hypot(dx,dy) 
      dx,dy = dx/dist,dy/dist 
      self.rect.x += dx * self.speed 
      self.rect.y += dy * self.speed 

class Character(Actor): 

    def __init__(self, x = 275, y = 250): 
     super(Character, self).__init__(x, y) 
     self.speed = 10 

    def update(self, enemies): 

     pygame.sprite.spritecollide(self, enemies, True) 

     key = pygame.key.get_pressed() 

     if key[pygame.K_w]: 
      self.rect.y -= self.speed 
     elif key[pygame.K_s]: 
      self.rect.y += self.speed 
     if key[pygame.K_a]: 
      self.rect.x -= self.speed 
     elif key[pygame.K_d]: 
      self.rect.x += self.speed 

     if self.rect.x > 1110: 
      self.rect.x = 1110 

     if self.rect.y < 20: 
      self.rect.y = 20 

     elif self.rect.y > 710: 
      self.rect.y = 710 
     if self.rect.x <20: 
      self.rect.x = 20 
     elif self.rect.x == 1110 and self.rect.y > 300 and self.rect.y < 400: 
      self.rect.x = 25 
     if self.rect.y == 20 and self.rect.x >500 and self.rect.x < 600: 
      self.rect.y = 715 
     elif self.rect.x == 20 and self.rect.y > 300 and self.rect.y < 400: 
      self.rect.x = 1090 
     if self.rect.y == 710 and self.rect.x >500 and self.rect.x < 600: 
      self.rect.y = 25 


pygame.init()        # Pygame is initialised (starts running) 

players = pygame.sprite.Group() 
screen = pygame.display.set_mode([1250,850]) # Set the width and height of the screen [width,height] 
pygame.display.set_caption("My Game")  # Name your window 
background_image = pygame.image.load("untilted.png") 

done = False        # Loop until the user clicks the close button. 

clock = pygame.time.Clock()     # Used to manage how fast the screen updates 
black = ( 0, 0, 0)     # Define some colors using rgb values. These can be 
white = (255, 255, 255)     # used throughout the game instead of using rgb values. 

# Define additional Functions and Procedures here 
score = 0 
bird = Character() 
blob = Enemy(random.randint(500,700),random.randint(300,400)) 
blob.target=bird 
all_sprites = pygame.sprite.Group([blob, bird]) 
enemies = pygame.sprite.Group([blob]) 

# -------- Main Program Loop ----------- 
while done == False: 

    for event in pygame.event.get():  # Check for an event (mouse click, key press) 
     if event.type == pygame.QUIT:  # If user clicked close window 
      done = True      # Flag that we are done so we exit this loop 

    screen.blit(background_image, (0, 0)) 

    all_sprites.update(enemies) 
    all_sprites.draw(screen) 

    pygame.display.update()     # Go ahead and update the screen with what we've drawn. 

    clock.tick(20)      # Limit to 20 frames per second 
    score += 1 
pygame.quit()  

注意如何在主循環只需要調用all_sprites.updateall_sprites.draw,其餘是由類EnemyCharacter自己完成。