欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现猜单词小游戏

程序员文章站 2022-05-02 20:19:15
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 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。