Объект NoneType не может быть вызван.питон - PullRequest
0 голосов
/ 07 апреля 2019

Я попытался написать небольшую игру для малинового пи на Python (например, игра "Not-Not"). Но я всегда получаю ошибку: 'Nonetype' Object is not callable, что на самом деле не имеет смысла? После экрана приветствия игра должна начинаться с обратного отсчета, а затем случайный цвет должен отображаться на дисплее. Если вы нажмете правую кнопку, это даст вам более высокий балл и будет продолжаться до тех пор, пока он не наберет 1000 баллов. Если вы нажмете не ту кнопку, вы получите минус 100 баллов. Если счет достигнет 0, игра должна закончиться.

Также я новичок в Python. Спасибо за ваши ответы :).

Это ошибка:

Traceback (most recent call last):
  File "game.py", line 316, in <module>
    Menu()
  File "game.py", line 114, in Menu
    Start_Game()
  File "game.py", line 139, in Start_Game
    Random_Sequency()
  File "game.py", line 118, in Random_Sequency
    random.choice(Sequenzen)()
TypeError: 'NoneType' object is not callable

Это код:

import RPi.GPIO as GPIO
import time
import lcddriver 
import random

lcd = lcddriver.lcd()

lcd.lcd_clear()

#Welcome

lcd.lcd_display_string("   Welcome to", 1)
lcd.lcd_display_string("   Not-Not :)", 2) 

#End Welcome 

InputPin = 35 #Rot
InputPin2 = 32 #Blau
InputPin3 = 37 #Gruen
InputPin4 = 38 #Gelb 

OutputPin = 11 #Rot
OutputPin2 = 12 #Blau
OutputPin3 = 13 #Gruen
OutputPin4 = 15 #Gelb 

BuzzerPin = 40 #Buzzer 

WaitTime = 0.5 #Wartezeit 

#SETUP

GPIO.setmode(GPIO.BOARD)

GPIO.setup(InputPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Input 1

GPIO.setup(InputPin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Input 2
GPIO.setup(InputPin3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Input 3
GPIO.setup(InputPin4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Input 4

GPIO.setup(OutputPin, GPIO.OUT) #Output 1

GPIO.setup(OutputPin2, GPIO.OUT) #Ouput 2
GPIO.setup(OutputPin3, GPIO.OUT) #Output 3
GPIO.setup(OutputPin4, GPIO.OUT) #Output 4 

#SETUP ENDE

#ENGINE

SCORE = 0

#Hauptmenue

def Menu(): 
    #Hauptmenue hier hin.
    Start_Game()
    #Hauptmenue Ende 

def Random_Sequency():
    random.choice(Sequenzen)()

#Spiel
def Start_Game():
    global SCORE

    lcd.lcd_clear()

    while(SCORE >= 0): 
        while(SCORE < 1000):

            lcd.lcd_display_string("Game starts in:", 1)
            lcd.lcd_display_string("3 Seconds.", 2)
            time.sleep(1)
            lcd.lcd_display_string("2 Seconds..", 2)
            time.sleep(1)
            lcd.lcd_display_string("1 Second...", 2)
            time.sleep(1)

            lcd.lcd_display_string("PRESS:", 1)

            Random_Sequency()

        lcd.lcd_display_string("Congratulations:", 1)
        lcd.lcd_display_string("YOU WON!", 2)
        time.sleep(5)
        SCORE = 0

        Menu() 



    lcd.lcd_display_string("    GAME", 1)
    lcd.lcd_display_string(" OVER :(", 2)
    time.sleep(5)
    SCORE = 0

    Menu()

#SEQUENZEN

#Blau
def Blue():
    global SCORE
    lcd.lcd_display_string("BLUE", 2)
    if(GPIO.input(InputPin2) == 1):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :)", 2)
        print("Knopf BLAU gedrueckt!")
        GPIO.output(OutputPin2, 0)
        print("Richtig!")
        time.sleep(WaitTime)
        GPIO.output(OutputPin2, 1)
        SCORE = SCORE + 50
        Random_Sequency()
    elif((GPIO.input(InputPin) == 1) or (GPIO.input(InputPin3) == 1) or (GPIO.input(InputPin4) == 1)):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :(", 2)
        print("Falsch!")
        GPIO.output(OutputPin, 0)
        GPIO.output(OutputPin3, 0)
        GPIO.output(OutputPin4, 0)
        time.sleep(WaitTime)
        GPIO.output(OutputPin, 1)
        GPIO.output(OutputPin3, 1)
        GPIO.output(OutputPin4, 1)
        SCORE = SCORE - 100
        Random_Sequency()
#Blau Ende

#Rot
def Red():
    global SCORE
    lcd.lcd_display_string("RED", 2)
    if(GPIO.input(InputPin) == 1):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :)", 2)
        print("Knopf ROT gedrueckt!")
        GPIO.output(OutputPin, 0)
        print("Richtig!")
        time.sleep(WaitTime)
        GPIO.output(OutputPin, 1)
        SCORE = SCORE + 50
        Random_Sequency()
    elif((GPIO.input(InputPin2) == 1) or (GPIO.input(InputPin3) == 1) or (GPIO.input(InputPin4) == 1)):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :(", 2)
        print("Falsch!")
        GPIO.output(OutputPin2, 0)
        GPIO.output(OutputPin3, 0)
        GPIO.output(OutputPin4, 0)
        time.sleep(WaitTime)
        GPIO.output(OutputPin2, 1)
        GPIO.output(OutputPin3, 1)
        GPIO.output(OutputPin4, 1)
        SCORE = SCORE - 100
        Random_Sequency()
#Rot Ende

#Gruen
def Green():
    global SCORE
    lcd.lcd_display_string("GREEN", 2)
    if(GPIO.input(InputPin3) == 1):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :)", 2)
        print("Knopf GRUEN gedrueckt!")
        GPIO.output(OutputPin3, 0)
        print("Richtig!")
        time.sleep(WaitTime)
        GPIO.output(OutputPin3, 1)
        SCORE = SCORE + 50
        Random_Sequency()
    elif((GPIO.input(InputPin) == 1) or (GPIO.input(InputPin2) == 1) or (GPIO.input(InputPin4) == 1)):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :(", 2)
        print("Falsch!")
        GPIO.output(OutputPin, 0)
        GPIO.output(OutputPin2, 0)
        GPIO.output(OutputPin4, 0)
        time.sleep(WaitTime)
        GPIO.output(OutputPin, 1)
        GPIO.output(OutputPin2, 1)
        GPIO.output(OutputPin4, 1)
        SCORE = SCORE - 100
        Random_Sequency()
#Gruen Ende

#Gelb
def Yellow():
    global SCORE
    lcd.lcd_display_string("YELLOW", 2)
    if(GPIO.input(InputPin4) == 1):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :)", 2)
        print("Knopf GELB gedrueckt!")
        GPIO.output(OutputPin4, 0)
        print("Richtig!")
        time.sleep(WaitTime)
        GPIO.output(OutputPin4, 1)
        SCORE = SCORE + 50
        Random_Sequency()
    elif(GPIO.input(InputPin) == 1 or GPIO.input(InputPin3) == 1 or GPIO.input(InputPin2) == 1):
        lcd.lcd_display_string("<><><><><><><><>", 1)
        lcd.lcd_display_string("      :(", 2)
        print("Falsch!")
        GPIO.output(OutputPin, 0)
        GPIO.output(OutputPin2, 0)
        GPIO.output(OutputPin3, 0)
        time.sleep(WaitTime)
        GPIO.output(OutputPin, 1)
        GPIO.output(OutputPin2, 1)
        GPIO.output(OutputPin3, 1)
        SCORE = SCORE - 100
        Random_Sequency()

Sequenzen = [Blue(), Red(), Green(), Yellow()]

#Inititation des Spieles 
try:
    while True:
        Menu()
except KeyboardInterrupt:
    GPIO.cleanup() 
#Initiation des Spieles Ende

#ENGINE ENDE

1 Ответ

1 голос
/ 07 апреля 2019

Беда в том, что когда вы делаете это:

Sequenzen = [Blue(), Red(), Green(), Yellow()]

вы вызываете эти функции тут и там, поэтому список содержит только их результаты . Как уже указывалось, ни одна из этих функций ничего не возвращает, поэтому все их результаты равны None, поэтому ваша ошибка.

Что вы действительно хотите сделать, так это иметь список только самих функций:

Sequenzen = [Blue, Red, Green, Yellow]

Кроме того, функции, вероятно, должны возвращать что-то: а именно обновленную оценку, а не использовать глобальную переменную.

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

...