参考文档
借鉴了这位大佬的博客及代码,键入代码后发现有很多报错,依次解决后成功运行
技术点:
C++中_kbhit()函数与_getch()函数
Windows API 坐标结构 COORD
句柄 HANDLE
获取句柄 GetStdHandle
光标的位置控 SetConsoleCursorPosition制
光标定位函数 gotoxy()与清屏函数clrscr()
报错解决
(1) warning C4244: “参数”: 从“time_t”转换到“unsigned int”,可能丢失数据
原因:一个简单的C的Hello World,如果用高版本的VS来编译,会有这种提示,这个是高版的VS默认不让使用scanf,fopen等函数,说是scanf,fopen等函数不安全,而代替其函数的是scanf_s,fopen_s等函数,后边有个"_s"的形式
解决:想要使用,可以在源文件开头加个:
#define _CRT_SECURE_NO_WARNINGS
预编时处理一下,加个宏而已,让其忽略安全检测
(2) warning C4996: ‘kbhit‘: The POSIX name for this item is deprecated.
原因:暂未得知
解决:将kbhit()
改为_kbhit()
,将getch()
改为_getch()
(3)运行报错:
原因:变量没有初始化。
解决:随便赋个初值,注意不能与操作按键的值一致
完整代码
/*********************************************************************
程序名: 贪吃蛇
*********************************************************************/
/*********************************************************************
程序名: 贪吃蛇
*********************************************************************/
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<ctime>
#include<stdlib.h>
#include<windows.h>
#include <conio.h>
using namespace std;
#define frame_width 50
#define frame_height 25
typedef struct{
int x, y;
} Food;
typedef struct{
int x[100], y[100], len, state;
} Snake;
void gotoxy(int x, int y); //最重要的一个函数,控制光标的位置
void print_map();
void get_newfood();//生成新食物
bool check_foodinsnake();//检查新食物有没有在蛇身上
void move_snake(); // 移动食物
void check_foodeating();//是否吃到食物
bool check_snakealive();//贪吃蛇是否还存活
//需要用到的全局变量
int score;
Snake snake;
Food food;
bool check_eaten;
int main()
{
system("color 0B");
do
{
printf("1:start\t2:exit\n");
char com2;
cin >> com2;
if (com2 == '2')
break;
system("cls");
score = 0, check_eaten = 0;
print_map()