21xrx.com
2025-06-29 06:22:03 Sunday
文章检索 我的文章 写文章
C++简单游戏代码合集
2023-07-11 18:55:12 深夜i     16     0
C++ 游戏代码 简单 合集

C++是一种高级编程语言,我们可以使用它来创建各种各样的应用程序,包括游戏。在本文中,我们将介绍一些简单的C++游戏代码,让您开始编写自己的游戏!

1. 石头,剪子,布游戏

这是一个非常简单的石头,剪子,布游戏的C++代码:

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
  int choice, computerChoice;
  srand(time(NULL));
  cout<<"请选择你的出拳:1. 石头 2. 剪子 3. 布"<<endl;
  cin>>choice;
  computerChoice=rand()%3 + 1;
  if(choice==1)
  {
    if(computerChoice==1)
    
      cout<<"平局"<<endl;
    
    else if(computerChoice==2)
    
      cout<<"你赢了"<<endl;
    
    else
    
      cout<<"你输了"<<endl;
    
  }
  else if(choice==2)
  {
    if(computerChoice==2)
    
      cout<<"平局"<<endl;
    
    else if(computerChoice==3)
    
      cout<<"你赢了"<<endl;
    
    else
    
      cout<<"你输了"<<endl;
    
  }
  else
  {
    if(computerChoice==3)
    
      cout<<"平局"<<endl;
    
    else if(computerChoice==1)
    
      cout<<"你赢了"<<endl;
    
    else
    
      cout<<"你输了"<<endl;
    
  }
  return 0;
}

2. 猜数字游戏

这是一个简单的猜数字游戏,它在1到100的范围内随机生成一个数字,玩家需要猜测这个数字是什么:

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
  int number, guess, tries=0;
  srand(time(NULL));
  number=rand()%100+1;
  cout<<"我想了一个1到100之间的数字,你猜是多少?"<<endl;
  do
  {
    cin>>guess;
    tries++;
    if(guess>number)
    再猜一次:"<<endl;
    
    else if(guess<number)
    
      cout<<"太小了
    else
    你猜对了!你猜了"<<tries<<""<<endl;
    
  }while(guess!=number);
  return 0;
}

3. 扫雷游戏

这是一个简单的扫雷游戏,玩家需要点击方格来揭开雷区,同时避免揭开雷区上的地雷:

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
const int ROWS=10;
const int COLS=10;
int main()
{
  int mines[ROWS][COLS];
  bool uncovered[ROWS][COLS];
  srand(time(NULL));
  for(int r=0; r<ROWS; r++)
  {
    for(int c=0; c<COLS; c++)
    {
      mines[r][c]=rand()%2;
      uncovered[r][c]=false;
    }
  }
  cout<<"欢迎来到扫雷!"<<endl;
  cout<<"键入坐标来揭开这个方格。例:2,3 表示第2行第3列。"<<endl;
  int row, col;
  bool gameover=false;
  do
  {
    for(int r=0; r<ROWS; r++)
    {
      for(int c=0; c<COLS; c++)
      {
        if(uncovered[r][c])
        {
          if(mines[r][c])
          
            cout<<".";
          
          else
          {
            cout<<".";
          }
        }
        else
        
          cout<<" ";
        
      }
      cout<<endl;
    }
    cout<<"请输入坐标:"<<endl;
    cin>>row>>col;
    if(mines[row-1][col-1])
    
      gameover=true;
      cout<<"你输了!"<<endl;
    
    else
    {
      uncovered[row-1][col-1]=true;
    }
  }while(!gameover);
  return 0;
}

这些C++游戏代码只是入门级别,但是您可以通过这些代码开始探索更复杂的游戏编程,继续提高您的技能和经验。祝您好运!

  
  

评论区