python实现猜单词小游戏

yipeiwu_com5年前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 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用pyinstaller打包exe文件的基本教程

前言 PyInstaller可以用来打包python应用程序,打包完的程序就可以在没有安装Python解释器的机器上运行了。PyInstaller支持Python 2.7和Python...

python如何创建TCP服务端和客户端

本文实例为大家分享了python创建tcp服务端和客户端的具体代码,供大家参考,具体内容如下 1.服务端server from socket import * from time i...

python-web根据元素属性进行定位的方法

1. 根据属性ID值进行定位 def test_find_element_by_id(self): # 定位搜索文本框 search_input = self.driver....

python机器学习之神经网络(三)

python机器学习之神经网络(三)

前面两篇文章都是参考书本神经网络的原理,一步步写的代码,这篇博文里主要学习了如何使用neurolab库中的函数来实现神经网络的算法。 首先介绍一下neurolab库的配置: 选择你所...

Python3编码问题 Unicode utf-8 bytes互转方法

为什么需要本文,因为在对接某些很老的接口的时候,需要传递过去的是16进制的hex字符串,并且要求对传的字符串做编码,这里就介绍了utf-8 Unicode bytes 等等。 #英文...