Текст не отображается в pygame

У меня есть две функции в классе под названием «NPC», которые будут использоваться для отображения текстового поля для отображения текста, который NPC должен сказать. Вот весь класс NPC для контекста:

class NPC(object):
        def __init__(self, path, x, y):
                self.image = pygame.image.load(path).convert_alpha()
                self.x = x
                self.y = y


        def spawn(self, surface):
                surface.blit(self.image, (self.x, self.y))

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

        def interact(self, text):
                textSize = pygame.font.Font("cour.ttf",28) #specify text size
                TextRect.center = (width/2, height/1.5) #where text will be
                TextSurf, TextRect = text_objects(text, largeText) #allow text to be positioned
                gameDisplay.blit(TextSurf, TextRect) #display text

                pygame.display.update() #updates screen

функция вызывается позже здесь:

person1 = NPC("talkToThis.png",100, 200)
pygame.display.flip() #paints screen
gameRun = True #allow game events to loop/be carried out more than once

while gameRun: #while game is running:

        key = pygame.key.get_pressed()

        for event in pygame.event.get():
                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:
                        if key[pygame.K_RETURN]:
                                person1.interact("hi")

Когда я запускаю код, ошибка не появляется, но когда я нажимаю клавишу ввода, сообщение не появляется. Сначала я подозревал, что это связано с тем, что шрифт не был в том же файле, что и код, однако после копирования / вставки он все еще не работал. У меня такое ощущение, что ошибка кроется где-то в двух функциях, связанных с текстом, возможно, в пропущенной части информации. Это также может быть связано с тем, что "person1" уже содержит три параметра, которые необходимы для функции "spawn" и для в этом.

полный код:

import pygame

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


        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))


class NPC(object):
        def __init__(self, path, x, y):
                self.image = pygame.image.load(path).convert_alpha()
                self.x = x
                self.y = y


        def spawn(self, surface):
                surface.blit(self.image, (self.x, self.y))

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

        def interact(self, text):
                textSize = pygame.font.Font("cour.ttf",28) #specify text size
                TextRect.center = (width/2, height/1.5) #where text will be
                TextSurf, TextRect = text_objects(text, largeText) #allow text to be positioned
                gameDisplay.blit(TextSurf, TextRect) #display text

                pygame.display.update() #updates screen



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

player = Player()
clock = pygame.time.Clock()

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


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:


        for event in pygame.event.get(): #all the events (movement, etc) to be here.
                if event.type == pygame.QUIT: #if the "x" is pressed
                        pygame.quit() #quit game
                        gameRun = False #break the loop.
                        quit()
                event = pygame.event.poll()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                        person1.interact("hi")

        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(40)

Отправьте полный код, пожалуйста

SampleText2k77 31.08.2018 12:44

@SamperMan Сейчас я добавлю к вопросу полный код.

Polybrow 31.08.2018 13:06

Хорошо, жду этого.

SampleText2k77 31.08.2018 13:07

@Polybrow проверь ответ

SampleText2k77 31.08.2018 13:12
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
4
141
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Во-первых, вам не нужен цикл for при проверке событий pygame. Затем выберите только один из способов поймать ваши ключевые события:

if pygame.key.get_pressed()[pygame.K_RETURN]:

или

event = pygame.event.poll()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:

Полный фрагмент кода:

while gameRun: #while game is running:

    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:
        person1.interact("hi")
    ....

спасибо, это помогло решить проблему ввода / нажатия кнопок. это также помогло найти другую ошибку, которая была в самой текстовой функции, поэтому я займусь этим

Polybrow 31.08.2018 13:22

Другие вопросы по теме