猜英语单词

文章介绍了一个使用Python编写的单词猜测游戏,代码从words.txt文件中读取单词列表,随机选择一个单词并提供提示。玩家可以通过输入字母或请求提示来猜测单词,直到猜出正确答案。游戏结束时可选择重新开始或退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

猜英语单词

  • 先新建一个后缀为.py的文件代码如下:
import random

#把单词储存在words.txt里一行一个单词
with open('words.txt', 'r') as file:
    words = [line.strip() for line in file]

def init():
    # 声明三个全局变量
    global word
    global tips
    global ranList

    # 随机获取单词列表里的一个单词
    word = list(words[random.randint(0, len(words) - 1)])

    # 随机数列表,存放着与单词长度一致的随机数(不重复)
    ranList = random.sample(range(0, len(word)), len(word))

    # 存放提示信息
    tips = list()
    # 初始化提示信息
    # 存放跟单词长度一致的下划线
    for i in range(len(word)):
        tips.append("_")
    # 随机提示两个字母
    tips[ranList[0]] = word[ranList[0]]
    tips[ranList[1]] = word[ranList[1]]




# 展示菜单
def showMenu():
    print("需要提示请输入'?'")
    print("结束游戏请输入'quit!'")


# 显示提示信息
def showtips():
    for i in tips:
        print(i, end=" ")
    print()


# 需要提示
def needTips(tipsSize):
    # 至少有两个未知字母
    if tipsSize <= len(word) - 3:
        tips[ranList[tipsSize]] = word[ranList[tipsSize]]
        tipsSize += 1
        return tipsSize
    else:
        print("已没有提示!")


# 主要运行函数↓↓↓↓↓↓
def run():
    print("------python关键字版本-------")
    init()
    tipsSize = 2
    showMenu()

    while True:
        print("提示:", end="")
        showtips()
        guessWord = input("猜一下这个单词:")
        # ''.join(word)>把word列表的内容转换成字符串
        if guessWord == ''.join(word):
            print("恭喜你,猜对了!就是%s!" % (''.join(word)))
            print("再猜一次")
            init()

        elif guessWord == '?':
            tipsSize = needTips(tipsSize)
        elif guessWord == 'quit!':
            break
        else:
            print("猜错了!")
            continue


run()
  • 再建一个words.txt文件(一行一个英语单词)

    如:

image.png

  • 最后祝大家高考顺利
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2301_77091173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值