Pygame-在特定区域设置碰撞边界的问题

时间:2018-09-21 16:28:34

标签: python pygame

---问题底部的完整代码---

我的计划是增加我的屏幕上被NPC占用的区域,以使播放器完全无法进入。我尝试通过在代码的NPC类中执行此方法来实现此方法,其中将播放器的y位置与npc的“ self.y” /当前y位置进行比较:

class NPC(object):
        def __init__(self, path, x, y):
                self.image = pygame.image.load(path).convert_alpha()
                self.x = x
                self.y = y
                self.width = self.image.get_width()
                self.height = self.image.get_height()
                self.hitbox = (self.x, self.y, self.width, self.height)


        def spawn(self, surface):
                surface.blit(self.image, (self.x, self.y))
                self.hitbox = (self.x, self.y, self.width, self.height)
                pygame.draw.rect(screen, (255, 255, 255), self.hitbox, 2)

        def collide(self, x, y, width, height):
                if self.y <= y <= self.y + self.height:
                        print("collide")
                        up = True
                else:
                        up = False
                        print("not")

我知道我还没有正确完成代码,我只是添加了应该阻止玩家出于测试目的而立即退出的部分。

但是由于某种原因,碰撞边界位于屏幕的顶部(而NPC不在),我怀疑这是由于程序从屏幕顶部测量了npc的高度(即:npc精灵的高度为32像素,因此碰撞区域位于屏幕顶部的前32像素)

阻止播放器移动的代码(这是“向上”布尔值在类外部所指的)也无法正常工作-这是由于可能未返回值吗?

完整代码:

import pygame
import time

progress = 0

pygame.init()
(width, height) = (600, 400) #specify window resolution
bg_colour = (100,20,156) #specify bg colour

player_path = "downChara.png" #specifies image path

moveDown = True
moveUp = True
moveRight = True
moveLeft = True

class Player(object): #representitive of the player's overworld sprite
        def __init__(self):
            self.image = pygame.image.load(player_path).convert_alpha() #creates image, the player_path variable allowing it to be updated
            self.X = (width/2) -16; # x co-ord of player
            self.Y = (height/2)-16; # y co-ord of player
            self.width = self.image.get_width()
            self.height = self.image.get_height()
            self.hitbox = (self.X, self.Y, self.width, self.height)


        def handle_keys(self, down, up, left, right): #handling the keys/inputs
                key = pygame.key.get_pressed()
                dist = 5 #distance travelled in one frame of the program
                if key[pygame.K_DOWN] and down == True: #if down
                        self.Y += dist #move down the length of dist
                        player_path = "downChara.png" #change image to down
                        self.image = pygame.image.load(player_path).convert_alpha()
                elif key[pygame.K_UP] and up == True: #if up
                        self.Y -= dist #move up the length of dist
                        player_path = "upChara.png" #change to up
                        self.image = pygame.image.load(player_path).convert_alpha()
                if key[pygame.K_RIGHT] and right == True: #etc.
                        self.X += dist
                        player_path = "rightChara.png"
                        self.image = pygame.image.load(player_path).convert_alpha()
                elif key[pygame.K_LEFT] and left == True:
                        self.X -= dist
                        player_path = "leftChara.png"
                        self.image = pygame.image.load(player_path).convert_alpha()


        def outX(coord): #"coord" acts the same as "self"
                return (coord.X)
        def outY(coord):
                return (coord.Y)


        def draw(self, surface): #draw to the surface/screen
            surface.blit(self.image, (self.X, self.Y))
            self.hitbox = (self.X, self.Y, self.width, self.height)
            pygame.draw.rect(screen, (255, 255, 255), self.hitbox, 2)
            return self.X, self.Y, self.width, self.height


class NPC(object):
        def __init__(self, path, x, y):
                self.image = pygame.image.load(path).convert_alpha()
                self.x = x
                self.y = y
                self.width = self.image.get_width()
                self.height = self.image.get_height()
                self.hitbox = (self.x, self.y, self.width, self.height)


        def spawn(self, surface):
                surface.blit(self.image, (self.x, self.y))
                self.hitbox = (self.x, self.y, self.width, self.height)
                pygame.draw.rect(screen, (255, 255, 255), self.hitbox, 2)

        def collide(self, x, y, width, height):
                if self.y <= y <= self.y + self.height:
                        print("collide")
                        up = True
                else:
                        up = False
                        print("not")
                ##if self.y < player.hitbox[1]

def text_objects(text, font):
        textSurface = font.render(text, True, (255, 255, 255))
        return textSurface, textSurface.get_rect()

def interact(text):
        textbox = pygame.transform.scale(pygame.image.load("bigbox.png"), (600, 111))
        textSize = pygame.font.Font("cour.ttf",28) #specify text size
        TextSurf, TextRect = text_objects(text, textSize) #allow text to be positioned
        TextRect.topleft = (12, 297) #where text will be
        screen.blit(textbox, (0, 289))
        screen.blit(TextSurf, TextRect) #display text
        pygame.display.update() #updates screen
        time.sleep(2)
        screen.fill(bg_colour, TextRect)



##def checker(array):
##  ##  check first value of each part of array (all numbers)
##  ##  compare it to progress
##  ##  if equal to or less than, cycle through rest of that part of array.
##  ##  if greater than, then ignore.
##  ##  e.g: progress = 49, NPC1 will still be on text "0", NPC2 will now be on "33" and NPC3 will be on "0"
##  
##        placeholderList = []
##  
##        for x in range(len(array)):
##                if array[x][0] <= progress:
##                        del placeholderList[0:]
##                        placeholderList.append(array[x][1:])
##        for x in range(len(placeholderList)):
##                passMe = placeholderList[x]
##                print (passMe)
##                npc.interact(passMe)


screen = pygame.display.set_mode((width, height)) #create window
pygame.display.set_caption('EduGame') #specify window name

player = Player()

playerx, playery, playerwidth, playerheight = player.draw(screen)

clock = pygame.time.Clock()

person1 = NPC("talkToThis.png",100, 200)
npc = NPC("test.png",0, 0)

def setup(text):
        for x in range(len(text)):
                passtext = text[x]
                interact(passtext)


boarderX = player.outX()
boarderY = player.outY()
##print (boarderX, boarderY) #making sure they both returned properly

pygame.display.flip() #paints screen
gameRun = True #allow game events to loop/be carried out more than once



while gameRun: #while game is running:
        person1text2 = [[0,"beginng","www","xxdqsd"],[1,"middle","aa"],[2,"end!"]]
        personText = ("hello","hi","bye")

        playerx, playery, playerwidth, playerheight = player.draw(screen)
        print(playerx, playery, playerwidth, playerheight)
        npc.collide(playerx, playery, playerwidth, playerheight)

        event = pygame.event.poll()
        if event.type == pygame.QUIT: #if the "x" is pressed
                pygame.quit() #quit game
                gameRun = False #break the loop.
                quit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
##                checker(person1text2)
                setup(personText)



        player.handle_keys(moveDown, moveUp, moveLeft, moveRight) #handle keys

        screen.fill(bg_colour) #draw background colour

        player.draw(screen) #draws player

        person1.spawn(screen)



        pygame.display.update()

        posX = player.outX()
        posY = player.outY()

        if posX > width - 32: #this is because the sprite's "X" is determined in the top left corner, meaning we have to subtract the width from the measurement
                moveRight = False
        else:
                moveRight = True
        if posX < 0:
                moveLeft = False
        else:
                moveLeft = True
        if posY > height - 32: #this is because the sprite's "X" is determined in the top left corner, meaning we have to subtract the width from the measurement
                moveDown = False
        else:
                moveDown = True
        if posY < 0:
                moveUp = False
        else:
                moveUp = True



        clock.tick(60)

这是一个很好的WIP,因此,如果您在检查过程中碰巧发现其他任何东西,可以随时提出来。

0 个答案:

没有答案