while循环中的函数不能运行多次

时间:2016-08-29 15:53:17

标签: python python-2.7

我正在写一个小游戏,试图学习python。在我的代码的底部,有一个while循环,它要求用户输入。如果该用户输入为yes,则应该更新变量encounter_prob。如果encounter_prob大于20,则应该调用该函数。我可以让这种行为发生,但只有一次。似乎没有再次通过if语句了。

import random

def def_monster_attack():
    monster_attack = random.randrange(1,6)
    return monster_attack

def def_player_attack():
    player_attack = random.randrange(1,7)
    return player_attack

def def_encounter_prob():
    encounter_prob = random.randrange(1,100)
    return encounter_prob

def def_action():
    action = raw_input("Move forward? Yes or No")
    return action

player = {
    'hp': 100,
    'mp': 100,
    'xp': 0,
    'str': 7
    }

monster = {
    'hp': 45,
    'mp': 10,
    'str': 6
    }

def encounter():
    while player['hp'] > 0 and monster['hp'] > 0:

        keep_fighting = raw_input("Attack, Spell, Gaurd, or Run?")
        if keep_fighting.startswith('a') == True:
            player_attack = def_player_attack()
            monster['hp'] = monster['hp'] - player_attack
            monster_attack = def_monster_attack()
            player['hp'] = player['hp'] - monster_attack
            print "player's hp is", player['hp']
            print "monster's hp is", monster['hp']

while player['hp'] > 0:
    action = def_action()

    if action.startswith('y') == True:
        encounter_prob = def_encounter_prob()
        if encounter_prob > 20:
            encounter()

2 个答案:

答案 0 :(得分:2)

它实际上两次调用函数encounter,但第一次最终通过将其hp减少到0或更低来杀死怪物,而第二次函数退出而没有进入while循环monster['hp'] > 0循环,因为False比较评估为hp。在每次新的遭遇中,怪物的print都不会被重置。

如果您在调试代码时遇到困难,请不要犹豫,在不同的地方放置一些/* Named searches allow to quickly reconfigure the decoder */ private static final String KWS_SEARCH = "wakeup"; private static final String FORECAST_SEARCH = "forecast"; private static final String DIGITS_SEARCH = "digits"; private static final String PHONE_SEARCH = "phones"; private static final String MENU_SEARCH = "menu"; /* Keyword we are looking for to activate menu */ private static final String KEYPHRASE = ""; /* Used to handle permission request */ private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1; private SpeechRecognizer recognizer; private HashMap<String, Integer> captions; private void runRecognizerSetup() { // Recognizer initialization is a time-consuming and it involves IO, // so we execute it in async task new AsyncTask<Void, Void, Exception>() { @Override protected Exception doInBackground(Void... params) { try { Assets assets = new Assets(TranslateActivity.this); File assetDir = assets.syncAssets(); setupRecognizer(assetDir); } catch (IOException e) { return e; } return null; } @Override protected void onPostExecute(Exception result) { if (result != null) { Toast.makeText(TranslateActivity.this,"Failed to initialize recognizer " + result, Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); } else { lblPrepare.setText("VOICE RECOGNITION READY"); lblSpeak.setVisibility(View.VISIBLE); recognizer.startListening(KWS_SEARCH); } } }.execute(); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { runRecognizerSetup(); } else { finish(); } } } @Override public void onDestroy() { super.onDestroy(); if (recognizer != null) { recognizer.cancel(); recognizer.shutdown(); } } /** * In partial result we get quick updates about current hypothesis. In * keyword spotting mode we can react here, in other modes we need to wait * for final result in onResult. */ @Override public void onPartialResult(Hypothesis hypothesis) { if (hypothesis == null) return; String text = hypothesis.getHypstr(); if(text.equals("")) { }else { Toast.makeText(TranslateActivity.this, text, Toast.LENGTH_SHORT).show(); } /*if (text.equals(KEYPHRASE)){ recognizer.cancel(); // <- You have to implement this recognizer.startListening(KWS_SEARCH); }/* switchSearch(MENU_SEARCH); else if (text.equals(DIGITS_SEARCH)) switchSearch(DIGITS_SEARCH); else if (text.equals(PHONE_SEARCH)) switchSearch(PHONE_SEARCH); else if (text.equals(FORECAST_SEARCH)) switchSearch(FORECAST_SEARCH); else Toast.makeText(TranslateActivity.this,text, Toast.LENGTH_SHORT).show();*/ } /** * This callback is called when we stop the recognizer. */ @Override public void onResult(Hypothesis hypothesis) { /* if (hypothesis != null) { String text = hypothesis.getHypstr(); makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); }*/ if (hypothesis!=null) { popupWindow.dismiss(); performAction(hypothesis); } } @Override public void onBeginningOfSpeech() { } /** * We stop recognizer here to get a final result */ @Override public void onEndOfSpeech() { /*if (!recognizer.getSearchName().equals(KWS_SEARCH)) switchSearch(KWS_SEARCH);*/ recognizer.stop(); popupWindow.dismiss(); } /*private void switchSearch(String searchName) { recognizer.stop(); // If we are not spotting, start listening with timeout (10000 ms or 10 seconds). if (searchName.equals(KWS_SEARCH)) recognizer.startListening(searchName); else recognizer.startListening(searchName); Toast.makeText(TranslateActivity.this,searchName, Toast.LENGTH_SHORT).show(); }*/ private void setupRecognizer(File assetsDir) throws IOException { // The recognizer can be configured to perform multiple searches // of different kind and switch between them recognizer = SpeechRecognizerSetup.defaultSetup() .setAcousticModel(new File(assetsDir, "en-us-ptm")) .setDictionary(new File(assetsDir, "cmudict-en-us.dict")) .setRawLogDir(assetsDir) // To disable logging of raw audio comment out this call (takes a lot of space on the device) .setKeywordThreshold(1e-45f) // Threshold to tune for keyphrase to balance between false alarms and misses .setBoolean("-allphone_ci", true) // Use context-independent phonetic search, context-dependent is too slow for mobile .getRecognizer(); recognizer.addListener(this); /** In your application you might not need to add all those searches. * They are added here for demonstration. You can leave just one. */ // Create keyword-activation search. recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE); // Create grammar-based search for selection between demos /* File menuGrammar = new File(assetsDir, "menu.gram"); recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar); // Create grammar-based search for digit recognition File digitsGrammar = new File(assetsDir, "digits.gram"); recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar); // Create language model search File languageModel = new File(assetsDir, "weather.dmp"); recognizer.addNgramSearch(FORECAST_SEARCH, languageModel); // Phonetic search File phoneticModel = new File(assetsDir, "en-phone.dmp"); recognizer.addAllphoneSearch(PHONE_SEARCH, phoneticModel);*/ } @Override public void onError(Exception error) { Toast.makeText(TranslateActivity.this,"Failed: "+error.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onTimeout() { /* switchSearch(KWS_SEARCH);*/ } public void performAction(Hypothesis hypothesis) { String strWord = hypothesis.getHypstr(); txtOriginal.setText(strWord); if(recognizer.getDecoder().lookupWord("abc") == null) { // do something } Toast.makeText(TranslateActivity.this, strWord, Toast.LENGTH_SHORT).show(); } 语句来检查数据的价值。这可以帮助您确定正在发生的事情。

答案 1 :(得分:0)

您的代码带有几个打印命令,向您展示如何在您完成所有编码时让您看到正在发生的事情。
哦!而且我把事情弄平了,不能给你带来不公平的优势:)

import random

def def_monster_attack():
    monster_attack = random.randrange(1,7)
    return monster_attack

def def_player_attack():
    player_attack = random.randrange(1,7)
    return player_attack

def def_encounter_prob():
    encounter_prob = random.randrange(1,100)
    return encounter_prob

def def_action():
    action = raw_input("Move forward? Yes or No")
    return action

player = {
    'hp': 45,
    'mp': 100,
    'xp': 0,
    'str': 7
    }

monster = {
    'hp': 45,
    'mp': 10,
    'str': 6
    }

def encounter():
    while player['hp'] > 0 and monster['hp'] > 0:
        keep_fighting = raw_input("Attack, Spell, Guard, or Run?")
        if keep_fighting.startswith('a') == True:
            player_attack = def_player_attack()
            monster['hp'] = monster['hp'] - player_attack
            monster_attack = def_monster_attack()
            player['hp'] = player['hp'] - monster_attack
            print "It's a carve up! Your health", player['hp']," the monster's ", monster['hp']
        else:
            print "Try attacking!"
while player['hp'] > 0 and monster['hp'] > 0:
    action = def_action()

    if action.startswith('y') == True:
        encounter_prob = def_encounter_prob()
        if encounter_prob > 20:
            encounter()
        else:
            print "Nothing happened all seems well"
    else:
        print "What are you going to stand there all day"
    if player['hp'] < 1: print "Oops! You're dead!"
    if monster['hp'] < 1: print "Hurrah! The monster's dead"