1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
|
#include <iostream>
#include <Windows.h> // for gotoxy
#include <conio.h> // for _kbhit()
using namespace std;
#define BULLET_SPEED 10;
struct Bullet
{
int x;
int y;
int timer; // simple timer to slow bullet a bit
bool alive;
Bullet() { alive = false; x = 0; y = 0; timer = BULLET_SPEED; }
void Update()
{
timer--;
if (timer == 0) {
if (alive) {
y--;
if (y < 1)
alive = false;
}
timer = BULLET_SPEED; // 10 seemed fine on this machine
}
}
};
void gotoxy(int x, int y);
void shootBullet(Bullet bullets[], int shipX, int shipY);
void updateBullet(Bullet bullets[]);
int main()
{
// for simplicity, max 10 bullets at a time
Bullet bullets[10];
bool playing = true;
char ch;
int shipXPos = 0, shipYPos = 40;
int bulletXPos = 0, bulletYPos = 0;
int bulletAlive = false;
do
{
// update the bullets pos
updateBullet(bullets);
// have i sensed a key press? - we need to do this
// because _getch would normally wait and therefore
// stop the updating of bullets etc.
if (_kbhit())
{
// yes, what was it?
ch = _getch();
switch (ch)
{
case 'z':
shipXPos--;
if (shipXPos < 0) shipXPos = 0;
break;
case 'x':
shipXPos++;
if (shipXPos > 50) shipXPos = 50;
break;
case ' ':
shootBullet(bullets, shipXPos, shipYPos-1);
break;
}
system("cls");
}
// draw the ship
gotoxy(shipXPos, shipYPos);
cout << " * ";
gotoxy(shipXPos, shipYPos + 1);
cout << "***";
} while (playing);
return 0;
}
// update all the bullets
void updateBullet(Bullet bullets[])
{
for (int i = 0; i < 10; i++)
{
if (bullets[i].alive) {
// bullet it active, before we update
// its position, we need to clear out
// the old one.
gotoxy(bullets[i].x+1, bullets[i].y);
cout << " ";
// update its position
bullets[i].Update();
// display it
gotoxy(bullets[i].x+1, bullets[i].y);
cout << "*";
}
}
}
// shoot the bullet
void shootBullet(Bullet bullets[], int shipX, int shipY)
{
for (int i = 0; i < 10; i++)
{
// find a bullet thats expired
if (!bullets[i].alive)
{
// found one, set its position.
bullets[i].x = shipX;
bullets[i].y = shipY;
bullets[i].alive = true; // flag it as active
}
}
}
// gotoxy
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
|