1

我有两个精灵,一个是我的角色,另一个是我的敌人。我如何让它们都具有 rect 属性,以便我可以在 pygame 中使用 rect 碰撞。任何事情都会对我有所帮助。谢谢。

这是我的代码:

import pygame,sys
from pygame.locals import *
pygame.init()

#WINDOW
WIDTH = 352
HEIGHT = 122
pygame.display.set_caption('My First Python Game')
screen=pygame.display.set_mode((WIDTH,HEIGHT))



#LOADING IMAGES
pg = "player.gif"
ey = "rat.gif"
bg = "y.gif"

enemy = pygame.image.load(ey)
player = pygame.image.load(pg)
spriteWidth, spriteHeight = player.get_rect().size
background = pygame.image.load(bg)

#MUSIC
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(-1,0.0)

#X & Y AXIS
x = 0
y = 0

 #Main Game Loop
   while True:
  for event in pygame.event.get():
    if event.type == QUIT:
     pygame.quit()
    sys.exit
    x = min(max(x, 0), WIDTH - spriteWidth)
    y = min(max(y, 0), HEIGHT - spriteHeight)
    screen.blit(background,[0,0])
    if event.type == pygame.KEYDOWN:
     if event.key == pygame.K_s:
      x  += 45
    screen.blit(player, (y,x))
    pygame.display.update()
    if x <= WIDTH:
      x = 0
    if y <= HEIGHT:
      y = 0
4

1 回答 1

3

创建一个播放器类,并这样做,在构造时传递图像:

class Player:

    def __init__(self, image, x, y, screen):
        self.image = image
        self.width = image.get_width()
        self.height = image.get_height()
        self.rect = pygame.Rect(x, y, width, height)
        self.screen = screen

    def move(self, dx, dy):
        self.rect.x += dx
        self.rect.y += dy

    def draw(self):
        self.screen.blit(self.image, (self.rect.x, self.rect.y))
于 2016-05-12T22:08:29.957 回答