python实现猜单词小游戏

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

相关文章

详解Django+uwsgi+Nginx上线最佳实战

什么是uwsgi? uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。WSG...

QML使用Python的函数过程解析

有2种方法: 一、 QML中定义一个信号,连接Python里的函数; 这里的函数不用特意指明为槽函数,普通函数即可。 QML的信号连接Python的函数 QML: 首先在QML中定...

Python中注释(多行注释和单行注释)的用法实例

前言 学会向程序中添加必要的注释,也是很重要的。注释不仅可以用来解释程序某些部分的作用和功能(用自然语言描述代码的功能),在必要时,还可以将代码临时移除,是调试程序的好帮手。 当然,添加...

python用于url解码和中文解析的小脚本(python url decoder)

复制代码 代码如下: # -*- coding: utf8 -*- #! python print(repr("测试报警,xxxx是大猪头".decode("UTF8").encode(...

Python 实现两个列表里元素对应相乘的方法

方法一: 结合zip函数,使用map函数: List1 = [1,2,3,4] List2 = [5,6,7,8] List3 = map(lambda (a,b):a*b,zip(...