当前位置:首页 » 《关于电脑》 » 正文

Python游戏(1) —— 猜单词_略略略咯的博客

12 人参与  2021年03月12日 13:43  分类 : 《关于电脑》  评论

点击全文阅读


猜单词小游戏

利用python实现一个猜单词的小游戏,需要导入的库为random库。
设计逻辑:从单词列表中随机选取一个单词,对单词里的字母顺序进行重新随机排序,从而产生新的字符串,玩家通过这个新的字符串猜测原单词。

对单词字母的重新排序

先处理这个程序的核心代码就是如何生成乱序的单词

jumble = ""
while word:
    position = random.randrange(len(word)) # 从单词中随机选取一个字符位置
    jumble += word[position] # 将字符拼接
    word = word[:position] + word[(position+1):] # 移除字符
print(jumble)

这里其实是将一个word字符串当成列表来处理了,从乱序字符串的拼接和word里字符的移除可以看出。

循环猜测环节

guess = input("输入你认为的单词:")
while True:
    if guess == correct:
        print("猜对了!")
        iscontinue = input("是否继续(Y/N):")
        break
    elif guess == ' ':
        exit(0)
    else:
        print("猜错了(输入空格可退出)")
        guess = input("继续猜:")

完整代码

import random

print("欢迎来到猜单词游戏")
words = ("python","hello","game","world","random") # 单词序列元组
jumble = ''
iscontinue = 'y'
while iscontinue.lower()=='y':
    word = random.choice(words) # 从单词元组中随机挑选一个单词
    correct = word # 利用新变量保持挑选的单词,用于之后的比较
    jumble = ""
    while word:
        position = random.randrange(len(word)) # 从单词中随机选取一个字符位置
        jumble += word[position] # 将字符拼接
        word = word[:position] + word[(position+1):] # 移除字符
    print(jumble)
    guess = input("输入你认为的单词:")
    while True:
        if guess == correct:
            print("猜对了!")
            iscontinue = input("是否继续(Y/N):")
            break
        elif guess == ' ':
            exit(0)
        else:
            print("猜错了(输入空格可退出)")
            guess = input("继续猜:")

参考来源

《Python游戏设计案例实战》


点击全文阅读


本文链接:http://zhangshiyu.com/post/16278.html

单词  字符  字符串  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1