PyGame开发bug?

时间:2015-12-09 21:46:10

标签: python python-3.x pygame

我正在使用Python 3.5.1开发一个Space Invaders克隆,并且偶然发现了一个我不确定如何解决的错误。我试图在窗口中保留一个精灵,我的代码只能保持精灵不要离开它的顶部和左侧。这是我的代码。感谢。

import pygame
import sys

width = 500
height = 700

white = (255, 255, 255)
black = (0, 0, 0)

score = 0

screen = pygame.display.set_mode([width, height])
screen_rect = screen.get_rect()

class Ship(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("player.png").convert()
        self.rect = self.image.get_rect()

    def update(self):
        pos_x, pos_y = pygame.mouse.get_pos()
        player_rect = self.image.get_rect()
        self.rect.x = pos_x
        self.rect.y = pos_y

        player_rect.clamp_ip(screen_rect)

class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("enemy.png").convert()
        self.rect = self.image.get_rect()

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("laser.png").convert()
        self.rect = self.image.get_rect()

player = Ship()
allSprites = pygame.sprite.Group()
allSprites.add(player)

running = True
while running == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(black)
    player.update()
    allSprites.draw(screen)

    pygame.display.flip()

pygame.quit()

2 个答案:

答案 0 :(得分:2)

该对象在Rect中已有self.rect个对象;您实际上并未在右侧clamp_ip调用Rect方法。

调用self.rect.clamp_ip(screen_rect)可能就足够了,甚至根本不需要获取图片Rect。如果我没记错的话,Sprite draw 的内置Group方法只能在精灵的Rect中绘制图像,所以请确保只更新精灵的Rect正确。

def update(self):
    self.rect.topleft = pygame.mouse.get_pos()
    if not screen_rect.contains(self.rect):
        self.rect.clamp_ip(screen_rect) 

答案 1 :(得分:0)

使用以下内容更改def update(self):

    def update(self):
        pos_tup = pygame.mouse.get_pos() # edit fix
        pos_x = pos_tup[0] # edit fix
        pos_y = pos_tup[1] # edit fix
        player_rect = self.image.get_rect()
        if pos_x < 0:
            self.rect.x = 0
        elif pos_x > width:
            self.rect.x = width
        else:
            self.rect.x = pos_x
        if pos_y < 0:
            self.rect.y = 0
        elif pos_y > height:
            self.rect.y = height
        else:
            self.rect.y = pos_y
        player_rect.clamp_ip(screen_rect)