Pong 游戏控制台版

Pong 游戏控制台版
我就直接上代码了欢迎来讨论

#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <ctime>
#include <cstdlib>
using namespace std;

#define WIDTH 120
#define HEIGHT 40

void setConsoleXY(int x, int y){
	COORD coord = { x, y };
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void hideCursor(){
	CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
}

int main(){
	int width = WIDTH / 2,height = HEIGHT / 2;
	int p_w = 4, p_h = 10, p_x = 0, p_y = HEIGHT / 2 - p_h;
	int p1 = 3;
	int p2_x = WIDTH - p_w;
	int p2_y = HEIGHT / 2 - p_h / 2;
	int p2 = 3;
	srand((unsigned)time(0));
	auto x = rand() % 3 + 1; //随机的速度
	auto y = rand() % 3 + 1;
	if (x % 2 == 1) 
		x = -x;
	if (y % 2 == 1)
		y = -y;
	while (true){
		width += x;
		height += x;
		setConsoleXY(0, 0); //初始坐标
		hideCursor();

		for (auto i = 0; i <= WIDTH; i++) //打印地图
			cout << '=';
		cout << '\n';

		for (auto j = 0; j < HEIGHT; j++){
			for (auto i = 0; i <= WIDTH; i++){
				if (i == width&&j == height){
					cout << '0';
				}
				else if (j >= p_y&&j < p_y + p_h&&i >= p_x&&i < p_x + p_w){
					std::cout << 'Z';
				}
				else if (j >= p2_y&&j < p2_y + p_h&&i >= p2_x&&i < p2_x + p_w){
					std::cout << 'Z';
				}
				else if (i == 0 || i == WIDTH / 2 || i == WIDTH){
					cout << '|';
				}
				else if (i == WIDTH / 2 && j == HEIGHT / 2){
					cout << '0';
				}
				else cout << ' ';
			}
			cout << '\n';
		}
		for (auto i = 0; i <= WIDTH; i++) 
			cout << '=';

		width += x;
		height += y;
		if (height <= 0 || height >= HEIGHT) //如果撞墙弹回
			y = -y;
		if (height < p_w&&height >= p_y&&height < p_y + p_h)
			y = -y;
		else if (height>HEIGHT - p_w&&height >= p_y&&height < p_y + p_h){
			y = -y;
		}
		if (width <= 0 || width >= WIDTH)
			x = -x;
		if (width < p_w&&height >= p_y&&height < p_y + p_h) {
			x = -x;
		}
		else if (width>WIDTH - p_w&&height >= p_y&&height < p_y + p_h){
			x = -x;
		}
		bool is_out = false;
		if (width < 0)
			is_out = true;
		else if (width>WIDTH - p_w)
			is_out = true;
		if (is_out){ //如果出界
			system("cls");
			width = WIDTH / 2;
			height = HEIGHT / 2;
			x = rand() % 3 + 1;
			y = rand() % 3 + 1;
			if (rand() % 2 == 1)
				x = -x;
			if (rand() % 2 == 1)
				y = -y;
		}
		char key;
		if (_kbhit()){		
			CreateThread
			key = _getch();		//获取键盘我在想怎么用CreateThread 线程来达到并发的效果
			if ((key == 'w' || key == 'W') && p_y > p1)
				p_y -= p1;
			else if ((key == 's' || key == 'S') && p_y + p1 + p_h < HEIGHT)
				p_y += p1;
			if (key == 72 && p2_y>p2)
				p2_y -= p2;
			else if (key == 80 && p2_y + p2+p_h<HEIGHT)
				p2_y += p2;
			//cout<<static_cast<int>(key);
		}
	}
	getchar();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值