下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
#include<stdio.h>
#include<Windows.h>//system
#include<time.h>//time
#include<conio.h>//kbhit
char dir = 1;//方向
int snake_x[1005], snake_y[1005], snake_len, head = 2, score = 0;
int food_x, food_y;//食物的坐标
void gotoxy(int x, int y){ //将光标移动到x,y坐标
COORD pos;
HANDLE hOutput;
pos.X = x;
pos.Y = y;
hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput, pos);
}
void gotoprint(int x, int y){
gotoxy(x, y); printf("■");
}
void creatgraph() {
for (int i = 0; i<58; i += 2) { //打印上下边框
gotoprint(i, 0);//打印第一行
gotoprint(i, 26);//打印最后一行
}
for (int i = 1; i < 26; i++) { //打印左右边框
gotoprint(0, i);//打印第一列
gotoprint(56, i);//打印最后一列
}
gotoprint(14,15);gotoprint(14,16);gotoprint(14,17);
snake_x[2] = 14; snake_y[2] = 15;//初始化蛇的坐标
snake_x[1] = 14; snake_y[1] = 16;
snake_x[0] = 14; snake_y[0] = 17;
}
void welcome() {
gotoxy(15,6); printf("/**********************************************/\n");
gotoxy(15,8); printf("/* */\n");
gotoxy(15,10); printf("/* 欢迎来到 贪吃蛇小游戏 ! */\n");
gotoxy(15,12); printf("/* wsad控制上下左右 */\n");
gotoxy(15,14); printf("/**********************************************/\n\n\n\n\n\n");
system("pause"); system("cls");//清除屏幕
}
void gotodelete(int x, int y){//清楚x,y坐标的内容
gotoxy(x, y); printf(" ");
}
void creatfood() {//创建食物
while (1) {
food_y = rand() % (25) + 1;//控制食物不超出边界
food_x = rand() % (53) + 2;
if (food_x % 2 != 0) food_x = food_x+1;
int flag = 0;
for (int i = head; i > head - snake_len; i--) {//判断食物的坐标与蛇的坐标是否重合
if (snake_x[i] == food_x && snake_y[i] == food_y) flag = 1;
}
if (!flag) break;
}
gotoxy(food_x, food_y); printf("⊙");
}
void Running() {//游戏引擎
int snake_len = 3, tx, ty;//下一步的坐标
creatfood();
while(1) {
if (_kbhit()) dir = _getch();//从键盘上获取按键
if (dir == 'w') {//上
tx = snake_x[head];
ty = snake_y[head] - 1;
}
else if (dir == 's') {//下
tx = snake_x[head];
ty = snake_y[head] + 1;
}
else if (dir == 'a') {//左
tx = snake_x[head] - 2;
ty = snake_y[head];
}
else if (dir == 'd') {//右
tx = snake_x[head] + 2;
ty = snake_y[head];
}
else continue;//按其他任意键暂停
if (tx < 1 || tx > 54 || ty < 1 || ty > 25) break;//达到边界就退出
if (tx == food_x && ty == food_y) {
score += 10; snake_len++; creatfood();//重新随机食物
}
else gotodelete(snake_x[head-snake_len+1], snake_y[head-snake_len+1]);
head++;
snake_x[head] = tx;
snake_y[head] = ty;
gotoprint(tx, ty); gotoxy(0, 27);//消除光标干扰
Sleep(200);//暂停200毫秒
}
system("cls");//清除屏幕
gotoxy(40, 10); printf("Game Over! Your Score is: %d\n", score);
system("pause");
}
int main() {
system("color 0B");//改变字体颜色
welcome();
creatgraph();
Running();
return 0;
}