zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    c#调用dll,::CoInitialize(NULL)出错
    使用 Anthem.NET 的常见回调(Callback)处理方式小结
    主题和皮肤学习
    得到任意网页源代码 (利用WebClient和WebRequest类)
    HTML marquee标签详解
    制作一个简单的天气预报
    CSS中的类class和标识id选择符(.和#号)
    String split '.'
    Map 的 clear() 方法会清空 Map对象
    sqLite 执行查询语句时报错__及SimpleCursorAdapter
  • 原文地址:https://www.cnblogs.com/csnd/p/12897060.html
Copyright © 2011-2022 走看看