Étape 7: Programmation code (c++)
::: copiez le code ci-dessous:::
#include
#include
#include
à l’aide de namespace std ;
bool gameOver ;
const int width = 50 ;
const int height = 20 ;
int x, y, fruitX, fruité, note ;
int tailX [100], tailY [100] ;
nTail int ;
enum eDirecton {arrêter = 0, gauche, droite, haut, bas} ;
eDirecton dir ;
void Setup()
{
gameOver = false ;
dir = arrêt ;
x = largeur / 2 ;
y = hauteur / 2 ; fruitX = rand() % largeur ;
Fruité = rand() % hauteur ;
score = 0 ;
}
void Draw()
{
System("CLS") ; System("Clear") ;
pour (int i = 0; i < largeur + 10; i ++)
cout << « # » ;
cout << endl ;
pour (int i = 0; i < hauteur; i ++)
{
pour (int j = 0; j < largeur; j ++)
{
Si (j == 0)
cout << « #basit » ;
Si (j’ai == y & & j == x)
cout << « O » ;
else if (i == fruité & & j == fruitX)
cout << « B » ;
d’autre
{
bool impression = false ;
pour (int k = 0; k < nTail; k ++)
{
Si (tailX [k] == j & & tailY [k] == j’ai)
{
cout << « o » ;
imprimer = true ;
}
}
Si (! imprimer)
cout << » ";
}
Si (j == largeur - 1)
cout << « #basit » ;
}
cout << endl ;
}
pour (int i = 0; i < largeur + 10; i ++)
cout << « # » ;
cout << endl ;
cout << "Score:" << partition << endl ;
cout << « faite par hafiz sayed abdul basit » ;
cout << endl ;
cout << "utilisez w, a, s, d pour contrôler le serpent" ;
}
Input() Sub
{
Si (_kbhit())
{
commutateur (_getch())
{
case « a » :
dir = gauche ;
rupture ;
affaire aurait ":
dir = droite ;
rupture ;
case « w » :
dir = vers le haut ;
rupture ;
de l’affaire ":
dir = vers le bas ;
rupture ;
case « x » :
gameOver = true ;
rupture ;
}
}
}
Sub Logic()
{
prevX int = tailX [0] ;
int prevY = tailY [0] ;
int prev2X, prev2Y ;
tailX [0] = x ;
tailY [0] = y ;
pour (int i = 1; i < nTail; i ++)
{
prev2X = tailX [i] ;
prev2Y = tailY [i] ;
tailX [i] = prevX ;
tailY [i] = prevY ;
prevX = prev2X ;
prevY = prev2Y ;
}
commutateur (dir)
{
affaire à gauche :
x--;
rupture ;
affaire à droite :
x ++ ;
rupture ;
affaire vers le haut :
y--;
rupture ;
boîtier bas :
y ++ ;
rupture ;
par défaut :
rupture ;
}
Si (x > largeur || x < 0 || y > hauteur || y < 0)
gameOver = true ;
Si (x > = largeur) x = 0 ; ElseIf (x < 0) x = largeur - 1 ;
Si (y > = hauteur) y = 0 ; ElseIf (y < 0) y = hauteur - 1 ;
pour (int i = 0; i < nTail; i ++)
Si (tailX [i] == x & & tailY [i] == y)
gameOver = true ;
Si (x == fruitX & & y == fruité)
{
score += 10 ;
fruitX = rand() % largeur ;
Fruité = rand() % hauteur ;
nTail ++ ;
}
}
int main()
{
Setup() ;
tandis que (! gameOver)
{
Draw() ;
Input() ;
Logic() ;
Sleep(60) ; Sleep(60) ; Vitesse recommandée est de 40 à 80 ;
}
return 0 ;
}