猜单词

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

class wordobj
{
public:
wordobj(){};
~wordobj(){};
bool getWord();
void selectWord();
const string& getSelWord();
bool isRight(char ch, int index);
private:
vector<string> svec;
int _size;
string _selectedWord;
char ch;
};

bool wordobj::getWord()
{
_size = 0;
ifstream infile("txt.txt");
if (!infile)
{
cout << "open file failed" << endl;
return false;
}
else
{
string word;
while (infile >> word)
{
svec.push_back(word);
}
_size = svec.size();
return true;
}
}

void wordobj::selectWord()
{
srand(_size);
int index = rand() % _size;
_selectedWord = svec[index];
cout << "the selected word is : ";
for (int i = 0; i != _selectedWord.size(); ++i)
{
cout <<"*";
}
cout << endl;
}

bool wordobj::isRight(char ch, int index)
{
return ch == _selectedWord[index];
}

const string& wordobj::getSelWord()
{
return _selectedWord;
}



int main()
{
wordobj wdj;
wdj.getWord();
wdj.selectWord();
int count = 0;
char ch;
cout << "please enter a character : ";
while (count < wdj.getSelWord().size())
{
cin >> ch;
if(!wdj.isRight(ch, count))
{
cout << "wrong, repeat entering this charactr /n (press '0' to quit) : ";
continue;
}
else
{
if ((count + 1) == wdj.getSelWord().size())
{
break;
}
cout << "enter the next character : ";
count ++;
}
}
cout << "successful!" << endl;
return 0;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!Python猜单词游戏是一个经典的编程练习项目,通常用于教学或娱乐。它基于随机选择一个单词,玩家需要猜测这个单词的所有字母。游戏流程一般包括以下几个步骤: 1. **字典选择**:从一个预先定义的单词列表中随机选取一个单词作为目标。 2. **隐藏单词**:用星号(*)表示目标单词中的每个字母,未猜中的字母隐藏起来。 3. **用户输入**:玩家输入他们猜测的字母,程序检查这个字母是否在目标单词中。 4. **更新隐藏单词**:如果玩家猜对了,将正确的字母显示出来;如果猜错了,提示字母是否存在于单词中。 5. **循环直到猜对**:当玩家猜出所有字母后,游戏结束并显示结果。 要实现这个游戏,你可以使用Python的内置模块如random和string,以及一些基本的控制结构(如循环和条件语句)。 下面是一个简单的Python猜单词游戏的概述代码框架: ```python import random # 准备单词列表 word_list = ["apple", "banana", "cherry", ...] # 选择随机单词 target_word = random.choice(word_list) hidden_word = '*' * len(target_word) # 游戏循环 while True: guess = input("Guess a letter: ").lower() if guess in target_word: hidden_word = hidden_word.replace('*', guess, 1) # 替换正确位置的 * else: print(f"{guess} is not in the word.") # 检查是否猜出全部单词 if '*' not in hidden_word: print(f"Congratulations! You guessed the word: {hidden_word}") break ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值