跳到正文

个人记录

人生第一份C++游戏

OMG_NOIP约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
获赞
3

版本

  1. v1当前

注:此游戏在我初二时创作,今天放到CSDN上骗奖励

人生第一份C++ ege 扩展游戏

规则:

1.不能碰到品红色方块。

2.不能立即切换当前方向的反方向。

3.以角色为中心5*5格范围内不会有红色方块刷新。

4.按空格暂停

C++
#include<bits/stdc++.h>
#include<graphics.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<cstring>
#define ll long long
using namespace std;
ll dif[4][2]={{-20,0},{0,-20},{20,0},{0,+20}},direction=2,x=700,y=400,tot=1,mp[1000][2];
char a[9]={'0','0','0','0','0','0','0','0','0'};
int main(){
	srand((int)time(0));
	initgraph(1400, 800); // 初始化绘图窗口的宽度和高度

	for(ll i=0;i<=1380;i+=20){
		mp[tot][0]=i;mp[tot][1]=0;
		tot++;
	}
	for(ll i=0;i<=1380;i+=20){
		mp[tot][0]=i;mp[tot][1]=780;
		tot++;
	}
	for(ll i=0;i<=780;i+=20){
		mp[tot][0]=0;mp[tot][1]=i;
		tot++;
	}
	for(ll i=0;i<=780;i+=20){
		mp[tot][0]=1380;mp[tot][1]=i;
		tot++;
	}

	setbkcolor(LIGHTCYAN);//设置窗口为浅青色
	setfont(30, 0, "宋体");
	ll k = 0;
	for ( ; k != key_esc; ) // key_esc是ege定义的按键常数
	{
		a[8]=tot%10+'0';
		a[7]=(tot%100)/10+'0';
		a[6]=(tot%1000)/100+'0';
		a[5]=(tot%10000)/1000+'0';
		a[4]=(tot%100000)/10000+'0';
		a[3]=(tot%1000000)/100000+'0';
		a[2]=(tot%10000000)/1000000+'0';
		a[1]=(tot%100000000)/10000000+'0';
		a[0]=(tot%1000000000)/100000000+'0';
		setbkcolor(LIGHTCYAN);//设置窗口为浅青色
		outtextxy(20, 20, a);
		ll x1=0 + rand() % ( 1400 -0 +1 );
		ll y1=0 + rand() % ( 800 -0 +1 );
		for(ll nd=1;nd<=2;nd++){
			while(abs(x-x1)<=40&&abs(y-y1)<=40){
			 	x1=0 + rand() % ( 1400 -0 +1 );
				y1=0 + rand() % ( 800 -0 +1 );
			}
			x1-=x1%20;
			y1-=y1%20;
			mp[tot+1][0]=x1;mp[tot+1][1]=y1;tot++;
		}


		//等待用户按键,并把得到的按键给k
		//如果你不想等待,可以在调用getch之前,使用kbhit检测是否有按键按下
		if ( kbhit() ){
			k = getch();

		}

		if(k==293&&direction!=3
		)direction=1;
		if(k==294&&direction!=4
		)direction=2;
		if(k==295&&direction!=1
		)direction=3;
		if(k==296&&direction!=2
		)direction=4;

		x+=dif[direction-1][0];y+=dif[direction-1][1];



		for(ll i=1;i<=tot;i++){
			if(x==mp[i][0]&&y==mp[i][1]){
				setbkcolor(LIGHTCYAN);//设置窗口为浅青色
				setfont(200, 0, "宋体");
				outtextxy(270,200,"game over");
				Sleep(500);
				getch(); // 暂停一下等待用户按键
   				closegraph(); // 关闭图形界面
			}
		}

		//设置填充颜色,一般为图形内部颜色
		setfillcolor(EGERGB(0x54, 0x54, 0x54));
		bar(x+1,y+1,x+19,y+19);

		Sleep(200);
		if(k==32){
			getch(); // 暂停一下等待用户按键
			k=0;
		}
		cleardevice();
		//设置填充颜色,一般为图形内部颜色
		setfillcolor(EGERGB(0xFC, 0x54, 0xFC));
		for(ll i=1;i<=tot;i++){
			bar(mp[i][0]+1,mp[i][1]+1,mp[i][0]+19,mp[i][1]+19);
		}

	}
	getch(); // 暂停一下等待用户按键
    closegraph(); // 关闭图形界面
	return 0;
}
原文