/*
日期:2019年3月2日
项目:双人弹跳球游戏
*/
#include<stdio.h>
#define MAX 100
#include<windows.h>
#include<conio.h>
int width, high; //游戏边界
int player1_x, player1_y, player2_x, player2_y; //定义玩家位置
int ball_x, ball_y; //球的位置
int map[MAX][MAX];
int score1, score2; //分数
int speed_x, speed_y; //小球速度
void start() //初始化变量
{
width = 40;
high = 20;
player1_x = 2;
player1_y = high/2;
player2_x = width-2;
player2_y = high/2;
ball_x = width/2;
ball_y = high/2;
score1 = 0;
score2 = 0;
speed_x = 1;
speed_y = 1;
}
/*左右边框为1 下边框为2 玩家挡板为3 小球为4 空白窗体为0*/
void startMap() //初始化地图
{
for(int i=0; i<=high; i++)
map[i][width] = 1;
for(int i=0; i<=high; i++)
map[i][0] = 1;
for(int i=1; i<width; i++)
map[high][i] = 2;
for(int i=0; i<high; i++)
{
for(int j=1; j<width; j++)
{
map[i][j] = 0;
}
}
for(int i=player1_y-2; i<=player1_y+2; i++)
map[i][player1_x] = 3;
for(int i=player2_y-2; i<=player2_y+2; i++)
map[i][player2_x] = 3;
map[ball_y][ball_x] = 4;
}
/* 隐藏光标 */
void hidCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; //头文件windows.h
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
/* 清除部分屏幕 */
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); //头文件windows.h
COORD pos; //pose表示一个结构体变量,COORD表示一个字符在控制台屏幕上的坐标
pos.X = width;
pos.Y = high;
SetConsoleCursorPosition(handle, pos);
}
void updateWithoutInput()//与输入无关的更新
{
ball_x = ball_x + speed_x;
ball_y = ball_y + speed_y;
/* 小球触碰挡板时 */
for(int i = player1_y-2; i<=player1_y+2; i++)
{
if((ball_x == player1_x) && (ball_y == i))
{
speed_x = -speed_x;
printf("\a");
}
}
for(int i = player2_y-2; i<=player2_y+2; i++)
{
if((ball_x == player2_x) && (ball_y == i))
{
speed_x = -speed_x;
printf("\a");
}
}
/* 小球触碰左右边界时 */
if(ball_x==width)
{
score1++;
printf("\a");
player1_x = 2;
player1_y = high/2;
player2_x = 38;
player2_y = high/2;
ball_x = width/2;
ball_y = high/2;
}
if(ball_x==0)
{
score2++;
printf("\a");
player1_x = 2;
player1_y = high/2;
player2_x = 38;
player2_y = high/2;
ball_x = width/2;
ball_y = high/2;
}
/* 小球触碰上下边界时 */
if((ball_y==0) || (ball_y==high))
{
speed_y = -speed_y;
}
}
void updateWithInput() //与输入相关的更新
{
char input;
if(kbhit())
{
input = getch();
if(input == 'w')
player1_y--;
if(input == 's')
player1_y++;
if(input == 'i')
player2_y--;
if(input == 'k')
player2_y++;
}
}
void show()
{
gotoxy(0, 0);
for(int i=0; i<=high; i++)
{
for(int j=0; j<=width; j++)
{
if(map[i][j]==1)
printf("|");
if(map[i][j]==2)
printf("~");
if(map[i][j]==3)
printf("*");
if(map[i][j]==4)
printf("o");
if(map[i][j]==0)
printf(" ");
}
printf("\n");
}
printf("\n***** 弹跳小球 *****\n");
printf("玩家一得分:%d 玩家二得分:%d\n",score1, score2);
printf("操作说明:WS控制玩家一移动 IK控制玩家二移动\n");
printf("***** 小球弹入左右边框积一分 *****\n");
}
int main(void)
{
start();
while(1)
{
hidCursor();
startMap();
show();
updateWithoutInput();
updateWithInput();
}
return 0;
}