C++小游戏:接球
本xxs人第一篇blog,如不好请提建议
感谢我亲爱的dady给我算法思路
我是分文件编写的,各文件代码如下:
一、头文件
1、map.h
#pragma once
#include <string>
std::string map[25] = {
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
};
int score, p_x = 4;
const int p_y = 22;
2、randnumber.h
#pragma once
#include <cstdlib>
#include <ctime>
using namespace std;
int randnumber(int begin, int end) {
srand(static_cast<unsigned int>(time(NULL)));
return (rand() % (end - begin + 1)) + begin + 1;
}
3、Ball.h
#pragma once
#include "map.h"
#include "randnumber.h"
class Ball {
private:
int B_speed;
int x;
int y;
public:
void down(int time);
Ball();
};
Ball::Ball() {
B_speed = randnumber(1, 5);
y = randnumber(0, 4);
x = randnumber(0, 9);
}
void Ball::down(int time) {
if (y > 22) {
map[y][x] = ' ';
B_speed = randnumber(1, 5);
x = randnumber(0, 9);
y = randnumber(0, 4);
}
if (time % B_speed == 0) {
map[y][x] = ' ';
y++;
}
if (x == p_x && y == p_y) {
score++;
B_speed = randnumber(1, 5);
y = randnumber(0, 4);
x = randnumber(0, 9);
}
map[y][x] = 'D';
}
二、主函数
main.cpp
#include "Catch_ball.h"
#include "Ball.h"
#include "randnumber.h"
#include "map.h"
#include <iostream>
#include <ctime>
#include <thread>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
vector<Ball> b;
void ball_loop(int n) {
int time = 0;
while (score < 20) {
map[p_y][p_x] = 'O';
for (int i = 3; i <= 23; i++) cout << map[i] << '\n';
cout << "score:" << score;
Sleep(100);
time = (time + 1) % 100000000;
for (int i = 0; i < n; i++) b[i].down(time);
system("cls");
}
}
int main() {
int n, time = 0;
char k = ' ';
cout << "Please input your hard level(<=10):";
cin >> n;
system("cls");
for (int i = 5; i > 0; i--) {
cout << i;
Sleep(1000);
system("cls");
}
for (int i = 0; i < n; i++) {
b.push_back(Ball());
Sleep(500);
}
system("cls");
cout << "start";
thread t(ball_loop, n);
t.detach();
while (score < 20) {
k = _getch();
if (k == 'a' && p_x != 0) {
map[p_y][p_x] = ' ';
p_x--;
}
else if (k == 'd' && p_x != 9) {
map[p_y][p_x] = ' ';
p_x++;
}
}
cout << "You win!\n\n\n";
system("pause");
return 0;
}
制作不易,点个赞吧!