欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python实现猜单词小游戏

时间:2020-10-08 13:28:18|栏目:Python代码|点击:

Python初学者小游戏:猜单词,供大家参考,具体内容如下

游戏逻辑:就像我们曾经英语学习机上的小游戏一样,电脑会从事先预置的词库中抽取单词,然后给出单词的字母数量,给定猜解次数,然后让玩家进行猜测,并给出每次猜测的正确字母与错误字母。

涉及知识点:random.randint(),print(),input()(raw_input())

参考实现代码:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
 
from __future__ import print_function 
import os 
import sys 
import random 
import time 
 
#单词库 
Words = ['apple','pear','banana'] 
 
#单词随机选择函数 
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 

上一篇:PYQT5 vscode联合操作qtdesigner的方法

栏    目:Python代码

下一篇:python实现用户登录系统

本文标题:python实现猜单词小游戏

本文地址:http://www.codeinn.net/misctech/8572.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有