python實現(xiàn)猜單詞小游戲
Python初學(xué)者小游戲:猜單詞,供大家參考,具體內(nèi)容如下
游戲邏輯:就像我們曾經(jīng)英語學(xué)習(xí)機上的小游戲一樣,電腦會從事先預(yù)置的詞庫中抽取單詞,然后給出單詞的字母數(shù)量,給定猜解次數(shù),然后讓玩家進行猜測,并給出每次猜測的正確字母與錯誤字母。
涉及知識點:random.randint(),print(),input()(raw_input())
參考實現(xiàn)代碼:
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import os import sys import random import time #單詞庫 Words = ['apple','pear','banana'] #單詞隨機選擇函數(shù) def getRandomWord(): global Words return Words[random.randint(0,len(Words)-1)] #猜測流程 def getGuess(): while True: guess = raw_input("Guess the Word: ") for letter in guess: if letter in wrongLetters: print("The char: " + letter + " you have already guessed") continue break return guess #判別顯示流程 def displayGame(secretLetters,wrongLetters,secretWord): global guess global count print("Info: ") for letter in guess: if letter in secretWord: secretLetters += letter else: wrongLetters += letter print("SecretLetters: ",end = '') for letter in secretLetters: print(letter,end = ' ') print() print("WrongLetters: ",end = '') for letter in wrongLetters: print(letter,end = ' ') print() print("Count: "+str(count)) blanks = '_'*len(secretWord) for i in range(len(guess)): if i >=len(secretWord): break if secretWord[i]==guess[i]: blanks = blanks[:i] + secretWord[i] + blanks[i+1:] print("Word: ",end = '') for i in blanks: print(i,end=" ") print() print() #主流程 secretLetters = '' wrongLetters = '' secretWord = '' guess = "" count = 6 os.system('cls') secretWord = getRandomWord() while True: displayGame(secretLetters,wrongLetters,secretWord) guess = getGuess() if guess == secretWord: print ("You win !") break else: if count <= 0: print("You lose !") break else: count -= 1 continue
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python使用Faker進行隨機數(shù)據(jù)生成
大家好,本篇文章主要講的是python使用Faker進行隨機數(shù)據(jù)生成,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02Python編程中Python與GIL互斥鎖關(guān)系作用分析
GIL互斥鎖用來保護Python世界里的對象,防止同一時刻多個線程執(zhí)行Python字節(jié)碼,確保線程安全,但也導(dǎo)致Python線程無法利用多核CPU優(yōu)勢,本文來探討Python將來是否有可能去除GIL2021-09-09基于Python3.7.1無法導(dǎo)入Numpy的解決方式
這篇文章主要介紹了基于Python3.7.1無法導(dǎo)入Numpy的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03