In this assignment you will create a single player version of the tron game. This program is very similar to the previous etch-a-sketch assignment.
kbhit()
function. It returns true if a key has been pressed. We will
use this function to "protect" the call to getch()
so that it doesn't stop the program. We will also introduce
a delay()
so the program doesn't run too quickly. The modifications look like this:
if(kbhit())
cKey = getch();
delay(20);
getpixel()
function from winbgim.h
. We will also use outtextxy
to display a message
that the game is over. Make sure to place this call before you use putpixel
.
if(getpixel(nX,nY) == WHITE)
outtextxy(200,340,"Game Over");
You will want the game to end if your trail crosses another trail or goes out of bounds.
main
function. Once you get the basic tron game working, break it up into functions—put the code that moves the Human player
in its own function:
void Border ();
void HumanMovement();
int nX = 320, nY = 240;
char cKey = '4';
int main ()
{
initwindow(640,480);
Border();
do
{
HumanMovement();
}while (cKey != 'q');
getch();
closegraph();
return 0;
}
HumanMovement()
, let’s call it ComputerMovement()
.
We’ll use HumanMovement()
as a basis for ComputerMovement()
.
What will be the same? different?
int nCompX = 320, nCompY = 360;
char cCompKey = 'u';
'u'
for up, etc.
void ComputerMovement()
{
switch (cCompKey)
{
case 'l':
nCompX--;
break;
//and so on
}
if(getpixel(nCompX,nCompY) != BLACK)
{
outtextxy(200,340,"Game Over Computer Loses");
cKey = 'q';
}
putpixel(nCompX, nCompY, YELLOW);
}
cCompKey
.
void ComputerMovement()
{
switch (cCompKey)
{
case 'l':
nCompX--;
//”Look” to the left
if(getpixel(nCompX-1,nCompY)!=BLACK)
cCompKey = 'u';
break;
//and so on. . .
outtextxy
. You may want to speed the game up as it progresses. If you find the delay()
function too slow, you might try writing your own DoNothing
function. Here's an example:
void DoNothing()
{
for(int nNum = 0; nNum < nTimes; nNum++);
}
I found that if I set nTimes
to 200000 I got a reasonable delay. You could add obstacles or a maze to make the
game more challenging. Be creative and have fun, your tron game doesn't have to look or work like any other.