In questo caso devi ricorrere ad altre due funzioni della conio : La kbhit() e la getch() che,
a differenza della gotoxy(), sono disponibili anche con il Dev-Cpp ed anche il MS Visual C++.
codice:
#include <windows.h>
#include <iostream>
#include <conio.h>
// Alcuni links :
// Character-Mode Applications http://msdn2.microsoft.com/en-us/library/ms682010.aspx
// Console Functions http://msdn2.microsoft.com/en-us/library/ms682073.aspx
using namespace std;
int gotoXY(short x, short y)
{
COORD dwCursorPosition = {x, y};
return SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE), dwCursorPosition);
}
void direzione(int &x, int &y);
int main()
{
int x=39, y=12, old_x=x, old_y=y;
int xp=30, yp=12, old_xp=xp, old_yp=yp;
int cicli;
char blocco=219, ch;
do
{
if(x!=old_x || y!=old_y)
{
gotoXY(old_x,old_y);
cout<<" ";
old_x = x;
old_y = y;
}
gotoXY(x, y);
cout<<blocco;
direzione(x, y);
for(cicli=0; cicli<10; cicli++)
{
Sleep(10);
if(kbhit()) // Se un tasto è premuto
{
ch=getch(); // Legge il suo valore
if(ch<=0) // Se è <=0 allora è un 'tasto di controllo'
{
ch=getch(); // Leggo il codice del tasto di controllo
gotoXY(0,0);
printf("Codice tasto : 0, %3d", ch);
switch(ch)
{
case 75: // Sinistra
if(xp>0)
xp--;
break;
case 77: // Destra
if(xp<79)
xp++;
break;
case 72: // Alto
if(yp>0)
yp--;
break;
case 80: // Basso
if(yp<24)
yp++;
break;
}
}
else
{
gotoXY(0,0);
printf("Codice tasto : %3d, ", ch);
switch( ch )
{
// Tasti 'normali'
}
}
gotoXY( old_xp, old_yp);
cout<<" ";
gotoXY( xp, yp);
cout<<"X";
old_xp=xp;
old_yp=yp;
}
}
}
while(ch!=27); // Premi ESC per uscire
return 0;
}
void direzione(int &x, int &y)
{
switch(rand()%4)
{
case 0:
if(y>0)
y--;
break;
case 1:
if(y<24)
y++;
break;
case 2:
if(x>0)
x--;
break;
case 3:
if(x<79)
x++;
break;
}
}
Non si può dire che le 'prestazioni' siano esaltanti