利用Python完成一个小游戏:随机挑选一个单词,并对其进行乱序,玩家要猜出原始单词

一 Python的概述以及游戏的内容

Python是一种功能强大且易于使用的编程语言,更接近人类语言,以至于人们都说它是“以思考的速度编程”;Python具备现代编程语言所应具备的一切功能;Python是面向对象

编程的语言,可以跟其他语言结合使用;Python在绝大多数操作系统上都可以运行,且是免费开源的。因为上述原因,Python变得十分流行以及成功。

本游戏属于猜字游戏,计算机从一组单词中随机挑一个出来,然后对其进行乱序(也就是让单词的字母随机排列)。玩家要猜出原始单词才算赢。由此可以大致总结程序的主要流程

1.先构建一组单词,作为数据来源,方便测试;

2.随机选择一个单词,并进行乱序,将乱序后的结果输出,供玩家猜测;

3.根据玩家的猜测结果,输出对应的信息

本实验是在Python3.3.5上完成,如果Python版本不一样,有些语法不能兼容导致报错!

二利用Python完成的代码

编程过程中出了一些语法结构注意之外,还要格外注意代码块以及缩进保持一致!缩进一致的才算是一个程序块。

#introuce random
import random        #引进随机模块

#set up dictionary
dictionary=("augment","encompass","scramble","prospective","reinstate",
                 "primordial","inexorable","discard","vigorous","commuter",
                 "appetite","grumble","mechanical","aesthetic","stereotype",
                 "compliment","civilization","discriminate","curse","sarcasm",
                 "insane","recipe","reinforce","jealous","anniversary")   #建立单词库,以元组的形式


right="Y"

print("Welcome to Word Guess! ")

while right=="Y":
    #randomly choose a vocabulary
    word=random.choice(dictionary)         #随机挑选一个单词

    score=100

    correct=word

    #break word   #将选出的单次进行乱序
    new_word=""

    for i in correct:
        position=random.randrange(len(word))
        new_word+=word[position]
        word=word[:position]+word[(position+1):]   #序列的索引,切片等操作

    #welcome interface

    print("The broken word is:",new_word)


    #user need to guess

    guess=input("Please input your guess:")   #玩家进行猜测

    while score>=60:
        if guess!=correct:
            guess=input("please try again:")
            score-=10;
        else:
            print("Congratulation!Your final score is:",score)
            break

    if score<60:
        print("Sorry,you are failed!")

    right=input("Play again?Y/N")     #如果想继续玩,则输入Y

print("Thanks for playing!")


input(" Press the enter key to exit")

三程序的检测结果

第一次输出的是打乱后的单词 oercnreif,正确的单词是reinforce,因为猜错了一次,所以扣了10分,最终成绩是90;

如果还想再来一局,则输入“Y”,即有新的单词出现。

原文地址:https://www.cnblogs.com/cxmhy/p/4360774.html