21xrx.com
2025-06-19 20:22:36 Thursday
登录
文章检索 我的文章 写文章
C++小游戏程序代码
2023-07-10 15:29:20 深夜i     14     0
C++ 小游戏 程序代码

C++作为一种面向对象的编程语言,为许多游戏开发者提供了创造游戏的机会。下面是一段简单的C++小游戏程序代码,供开发者参考:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
  // 随机数生成器种子
  srand(static_cast<unsigned int>(time(0)));
  // 谜底单词列表
  const int NUM_WORDS = 5;
  const string WORDS[NUM_WORDS] =
  
    "glasses";
  // 随机选择一个谜底
  int choice = (rand() % NUM_WORDS);
  string word = WORDS[choice];
  int length = word.length();
  // Jumble单词
  string jumble = word; // 初始化jumble与word的值相同
  for (int i = 0; i < length; ++i)
  {
    int index1 = (rand() % length);
    int index2 = (rand() % length);
    char temp = jumble[index1];
    jumble[index1] = jumble[index2];
    jumble[index2] = temp;
  }
  // 游戏引擎
  cout << "\tWelcome to Word Jumble!" << endl << endl;
  cout << "Unscramble the letters to make a word." << endl;
  cout << "Enter 'quit' to quit the game." << endl << endl;
  cout << "The jumble is: " << jumble;
  string guess;
  cout << "\n\nYour guess: ";
  cin >> guess;
  while ((guess != word) && (guess != "quit"))
  {
    cout << "Sorry, that's not it.";
    cout << "\n\nYour guess: ";
    cin >> guess;
  }
  if (guess == word)
  
    cout << endl << endl << "That's it! You guessed it!" << endl;
  
  cout << endl << "Thanks for playing." << endl;
  return 0;
}

该程序中,程序先生成一个随机数生成器种子,并定义了一个包含5个谜底单词的字符串常量数组。然后程序从谜底中随机选择一个单词,并进行Jumble。最后,程序通过一个游戏引擎来将Jumble后的单词和用户输入的单词进行比较,直到用户猜中或者输入了“quit”。

这段代码可以在控制台中运行,是一个简单而有趣的猜单词小游戏。此外,通过修改谜底单词列表和程序中的其他参数,可以对游戏进行不同的定制和升级,增加游戏的趣味性和挑战性。

  
  

评论区