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设计】。

相关文章

在OpenCV里使用特征匹配和单映射变换的代码详解

在OpenCV里使用特征匹配和单映射变换的代码详解

前面已经学习特征查找和对应匹配,接着下来在特征匹配之后,再使用findHomography函数来找出对应图像的投影矩阵。首先使用一个查询图片,然后在另外一张图片里找到目标对象,其实就是想...

django manage.py扩展自定义命令方法

django manage.py扩展自定义命令方法

# django manage.py扩展自定义命令 环境: mac django1.10.3 在实际的项目开发过程中,我们可能要执行某脚本初始化数据库,可能要启动多个服务,比...

在Python中操作文件之seek()方法的使用教程

 seek()方法在偏移设定该文件的当前位置。参数是可选的,默认为0,这意味着绝对的文件定位,它的值如果是1,这意味着寻求相对于当前位置,2表示相对于文件的末尾。 没有返回值。...

解析PyCharm Python运行权限问题

解析PyCharm Python运行权限问题

先通过 which python 获得 python 指令所在路径: $ which python /usr/bin/python 如上得到了其所在路径是 /usr/bin/pyt...

使用pyqt5 tablewidget 单元格设置正则表达式

使用pyqt5 tablewidget 单元格设置正则表达式

tablewidget pyqt5的tablewidget组件比较特殊,每个方格可以装载其他组件来搭配实现不同的效果,所以在qtdesigner上找不到可视化直接设置mask或者其他可...