2016-02-26 2 views
0

Я уже давно работаю над проектом в python, и я не могу назвать главную функцию. Я искал какое-то время, но я не могу заставить его работать. Сейчас проблема в том, что я не могу назвать главную функцию. Раньше было, что после того, как программа перешла к основной функции, как только она не вернется к основной функции, но теперь она даже не войдет в основную функцию, и я не могу ее вызвать из оболочки. Может кто-нибудь мне помочь? Вот мой код.Невозможно использовать функции в Python

#!/usr/bin/python 
# I only have the above part in case the 
# end user does not have python 

# Wizard's Quest Copyright (c) 2016 by GrayHat4Life 
# This software is open source and may be distributed freely 

# Prepare the program 
import sys, random 

# Set up some variables & begin the story 
global health 
health = 10 
global enemiesKilled 
enemiesKilled = 0 
print("You are a wizard travelling through the kingdom") 
print("Your quest: to save the kingdom by placing the Gem of Karn in its rightful place, the Tower of Souls") 
# Main gameplay loop 
def main(): 
# Battle code 
# Set up the battle variables 
    enemyList = ["Goblin", "Witch", "Dark Mage", "Dark Knight", "Theif", "Troll", "Orc"] 
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 
# Prepare the battles 
    print("As you are walking through the Forest of Doom, a " + random.choice(enemyList) + " appears on the path in front of you!") 
# This part isn't very usefull, it's only to give the 
# player the illusion of free will. It's actually a kind of gambling game :s 
    input("What spell do you use to attack it? ") 
# The attack strengths 
    attack = random.choice(numbers) 
    enemyAttack = random.choice(numbers) 
# Let the battle begin! 
    if attack > enemyAttack: 
     health = health - 1 
     print("Your attack failed and you've been hit! You narrowly escape the enemy and continue your quest") 
     main() 
    elif enemyAttack > attack: 
     enemiesKilled = enemiesKilled + 1 

# This loop gives the user the ability to win. And lose. :D 
while True: 
    if enemiesKilled == 10: 
     print("You've finally made it to the end of your quest!") 
     print("You place the Gem of Karn in the soul sphere and save the kingdom!") 
     sys.exit() 
    elif health == 0: 
     print("The damage was too much.") 
     print("You bleed out in the middle of the forest, alone and friendless.") 
     print("GAME OVER") 
     sys.exit() 

Спасибо!

+0

Вы никогда не называете 'основной()' функции. Он не вызывается автоматически. – Barmar

+0

Я попытался вызвать его, прежде чем он подошел, и возникла синтаксическая ошибка (очевидно). Думаю, я решил проблему с помощью Stack Overflow. – GrayHat4Life

ответ

0

Я не вижу, как вы сначала назовете метод main().

В настоящее время, вы входите в while True: и ни одно из условий enemiesKilled == 10: или health == 0: истинны

Ваш код должен следовать этой структуре, если вы ждете, чтобы выполнить его

import somestuff 

def main(): 
    # do something here 

if __name__ == '__main__': 
    # call the main function 
    main() 

И если вы хотите while True: кусок , то я рекомендовал бы что-то подобное вместо этого, чтобы остановить бесконечный цикл

if __name__ == '__main__': 
    # call the main function 
    while enemiesKilled != 10 or health != 0: 
     main() 

    if enemiesKilled == 10: 
     print("You've finally made it to the end of your quest!") 
     print("You place the Gem of Karn in the soul sphere and save the kingdom!") 
    elif health == 0: 
     print("The damage was too much.") 
     print("You bleed out in the middle of the forest, alone and friendless.") 
    print("GAME OVER") 
0

Python не имеет основной функции. Сначала определите свои функции, чтобы интерпретатор знал о них. Затем он выполнит первый оператор после последнего «возврата» и последующих операторов после этого.

Правильный синтаксис для питона:

#!/usr/bin/python 

# Function definition is here 
def printme(str): 
    "This prints a passed string into this function" 
    print str 
    return; 

# Now you can call printme function 
printme() 
+0

Python также не нуждается в завершающих полуколониях или неявных операторах возврата –

Смежные вопросы