Почему pygame.MOUSEBUTTONDOWN никогда не равняется моей кнопке, даже если пользователь нажимает на нее? - PullRequest
0 голосов
/ 14 января 2019

В настоящее время я работаю над школьным проектом, использующим Python, и в идеале проект должен создать любую программу, использующую абстракцию или алгоритмы. Тем не менее, я озадачен этой проблемой, которая у меня была в течение нескольких дней. Я использую Python с реализацией Pygame для создания Vision Quiz, и я использую кнопки в качестве ответов с несколькими вариантами ответов. Всякий раз, когда я нажимаю на правильную кнопку, она всегда говорит, что она неправильная, и я некоторое время не мог пройти эту часть. Пожалуйста, помогите мне.

Ссылка Pastebin, если необходимо: https://pastebin.com/BFPr6x6a Форматирование кода здесь:

#Christopher Ticona
#Vision and Hearing examination

import pygame #All implementation of pygame itself

pygame.init()

#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0) 

#Images
imageOne = pygame.image.load("imageOne.gif")
imageOne = pygame.transform.scale(imageOne,(200,200))
imageTwo = pygame.image.load("imageTwo.png")
imageTwo = pygame.transform.scale(imageTwo, (400,400))

#Messages and questions
welcome = "Welcome to my program! Let's get started. Today, we'll be examining your eyesight/color and hearing to see if you need any glasses or support for your sense. Don't worry, this could help your health!"
summaryProgram = "There will be multiple images and sounds when you're answering the exam to test yourself on hearing, eyesight, and color blindness. Be honest and don't judge yourself if you get it wrong! Good luck!"

questionOne = "1) What do you see?: "
questionTwo = "2) What's 1 letter from the 20/20 vision section?"

#Screen to display graphics
screen = pygame.display.set_mode((1550, 720))
screen.fill(white)
pygame.display.set_caption("Vision and Hearing Examination")

class Button:
    def __init__(self, rect, command):
        self.rect = pygame.Rect(rect)
        self.image = pygame.Surface(self.rect.size).convert()
        self.image.fill((red))
        self.function = command

    def get_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            self.on_click(event)

    def on_click(self, event):
        if self.rect.collidepoint(event.pos):
            self.function()

    def draw(self, surf):
        surf.blit(self.image, self.rect)


def button_was_pressed():
    if (pygame.MOUSEBUTTONDOWN == answerOne):
        printText("You're correct! 1 Point", 15, 350, 100, black)
    else:
        printText("You're incorrect! Keep going!", 15, 350, 100, black)


def button_was_pressed1():
    if (pygame.MOUSEBUTTONDOWN == answerTwo):
        printText("You're correct! 1 Point", 15, 350, 300, black)
    else:
        printText("You're incorrect! Keep going!", 15, 350, 300, black)

def printText(txtText, Textsize , Textx, Texty, Textcolor):
    #User's font
    myfont = pygame.font.SysFont('Comic Sans MS', Textsize)
        #Input text
    label = myfont.render(txtText, 1, Textcolor)
    #Coordinates of text
    screen.blit(label, (Textx, Texty))
    #Show the full display
    pygame.display.flip()

def textButton(text,x,y):
    font = pygame.font.SysFont("Comic Sans MS", 30)
    textsurface = font.render((text), True, (0,0,0))
    button_rect = textsurface.get_rect(topright=(x,y))
    screen.blit(textsurface, button_rect)

#Font is automatically Comic Sans MS (Change if needed)
#printText(Text, Size, X, Y, Color)
welcomingMessage = printText(welcome, 15, 5, 10, black)
explanation = printText(summaryProgram, 15, 5, 30, black)
questionOne = printText(questionOne, 15, 5, 100, black)
questionTwo = printText(questionTwo, 15, 5, 300, black)

#Images displayed to the quiz
screen.blit(imageOne,(700,100))
screen.blit(imageTwo,(600,300))

#Button(rect=(x, y, height, width), command=button_was_pressed)
#Question 1
btn = Button(rect=(25,120,105,30), command=button_was_pressed)
btn1 = Button(rect=(200,120,105,30), command=button_was_pressed)
btn2 = Button(rect=(25,180,105,30), command = button_was_pressed)
btn3 = Button(rect=(200,180,105,30), command = button_was_pressed)
#Question 2
btn4 = Button(rect=(25,320,105,30), command=button_was_pressed1)
btn5 = Button(rect=(200,320,105,30), command=button_was_pressed1)
btn6 = Button(rect=(25,380,105,30), command=button_was_pressed1)
btn7 = Button(rect=(200,380,105,30), command=button_was_pressed1)

answerOne = btn
answerTwo = btn6

done = False
while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                        exit()
                        quit()
                btn.get_event(event)
                btn1.get_event(event)
                btn2.get_event(event)
                btn3.get_event(event)
                btn4.get_event(event)
                btn5.get_event(event)
                btn6.get_event(event)
                btn7.get_event(event)
        btn.draw(screen)
        btn1.draw(screen)
        btn2.draw(screen)
        btn3.draw(screen)
        btn4.draw(screen)
        btn5.draw(screen)
        btn6.draw(screen)
        btn7.draw(screen)

        #Text over button
        #Question 1
        textButton("8", 90, 110)
        textButton("3", 250,110)
        textButton("7", 90, 170)
        textButton("18", 250, 170)
        #Question 2
        textButton("B", 90, 310)
        textButton("A", 250, 310)
        textButton("O", 90, 370)
        textButton("X", 250, 370)
        pygame.display.update()

1 Ответ

0 голосов
/ 14 января 2019

Как указывает @UnholySheep, вы передаете функцию button_was_pressed в ваши Button объекты. Эта функция содержит эту строку:

if (pygame.MOUSEBUTTONDOWN == answerOne):

К сожалению, pygame.MOUSEBUTTONDOWN - это константа, предоставляемая библиотекой pygame - она ​​может или не может быть равна answerOne один раз, но она не всегда будет равна нужному «правильному» индикатору (если вы не сделаете Ваши вопросы всегда имеют один и тот же ответ: «всегда выбирайте ответ« С »» или что-то в этом роде.

Позвольте мне сделать несколько предложений:

  1. Переместите свой чек для кнопки мыши 1 в отдельную функцию, принимая событие:

    def was_mouse1_click(event):
        """Return true if event is a mouse button 1 down event"""
        pass
    
  2. Напишите метод на кнопке, чтобы определить, был ли щелчок внутри области кнопки.

  3. Напишите функцию для определения, какая кнопка была нажата, или Нет.

  4. Очистите ваш код, чтобы ваш основной цикл был коротким и приятным:

    buttons = [btn1, btn2, btn3, btn4]
    
    while not done:
        for event in pygame.event.get():
            if was_quit(event):
                done = true
                break
            elif was_mouse1_click(event):
                btn = which_button_was_clicked(event, buttons)
    
                if btn is None:
                    # click outside buttons? ignore
                    continue
                elif btn == right_answer:
                    celebrate()
                else:
                    wrong()
            else:
                # Not a quit, not a click, ignore it.
                pass
    
        # draw/update screen, etc.
    
    # broke out of while? we're done
    exit()
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...