[Programme C ++] Jeu de serpent

Récemment , je suis obsédé par l'écriture de jeux, bien qu'il s'agisse de versions DOS simples (la précédente tentative de programmation visuelle a échoué), de tic-tac-toe , de gomoku et de labyrinthes en mouvement , j'ai trouvé un serpent qui n'a pas été conçu. Le programme suivant a donc été conçu.

programme

// This is a simple snake game.

#include <iostream>
#include <string>
#include <vector>
#include <cstddef>
#include <Windows.h>
#include <conio.h>
#include <random>
#include <ctime>
#include <deque>
using namespace std;

struct location {
    
    
	unsigned x, y;
}loc1, loc2;

int state = 0;
int ret = 4; // head right by default
unsigned cnt = 0;
unsigned score = 0;
char p[25][30]; // the board
vector<location> vec;
deque<location> snake;

void p_def() // define p
{
    
    
	for (int i = 0; i != 25; i++)
	{
    
    
		if (i != 0 && i != 24)
		{
    
    
			p[i][0] = p[i][29] = '*';
			for (int j = 1; j != 29; j++)
				p[i][j] = ' ';
		}
		else
		{
    
    
			for (int j = 0; j != 30; j++)
				p[i][j] = '*';
		}
	}
	p[13][5] = 'O'; // body
	p[13][6] = '@'; // head
	loc1.x = 13;
	loc1.y = 6; // the initial location of the head of the snake
	loc2.x = 13;
	loc2.y = 5; // the initial location of the tail of the snake
	snake.push_front(loc2); // store the first location of the snake tail
}

void input(char c1, char c2)
{
    
    
	c1 = _getch();
	c2 = _getch();
	switch (c2)
	{
    
    
	case 72: // up
		if (ret != 2)
			ret = 1;
		break;
	case 80: // down
		if (ret != 1)
			ret = 2;
		break;
	case 75: // left
		if (ret != 4)
			ret = 3;
		break;
	case 77: // right
		if (ret != 3)
			ret = 4;
		break;
	default:
		break;
	}
}

void print()
{
    
    
	for (int i = 0; i != 25; i++)
	{
    
    
		for (int j = 0; j != 30; j++)
			std::cout << " " << p[i][j];
		std::cout << endl;
	}
}

void ran() // generate a random food for the snake to eat
{
    
    
	default_random_engine random1, random2;
	for (int i = 0; i != 644; i++)
	{
    
    
		unsigned ran1 = random1() % 23 + 1; // ranging from 1 to 23
		unsigned ran2 = random2() % 28 + 1; // ranging from 1 to 28
		location ran_l;
		ran_l.x = ran1;
		ran_l.y = ran2;
		vec.push_back(ran_l);
	}
}

void move()
{
    
    
	switch (ret)
	{
    
    
	case 1: // up
		if (p[loc1.x - 1][loc1.y] == 'O' || p[loc1.x - 1][loc1.y] == '*')
			state = 1; // indicate the end of the game
		else
		{
    
    
			if (p[loc1.x - 1][loc1.y] == '#')
			{
    
    
				score++;
				snake.push_front(loc1);
			}
			else
			{
    
    
				p[snake.back().x][snake.back().y] = ' '; // delete the end of the tail
				snake.pop_back();
				snake.push_front(loc1); // former head -> front of the tail
			}
		}
		--loc1.x;
		break;
	case 2: // down
		if (p[loc1.x + 1][loc1.y] == 'O' || p[loc1.x + 1][loc1.y] == '*')
			state = 1; // indicate the end of the game
		else
		{
    
    
			if (p[loc1.x + 1][loc1.y] == '#')
			{
    
    
				score++;
				snake.push_front(loc1);
			}
			else
			{
    
    
				p[snake.back().x][snake.back().y] = ' '; // delete the end of the tail
				snake.pop_back();
				snake.push_front(loc1); // former head -> front of the tail
			}
		}
		++loc1.x;
		break;
	case 3: // left
		if (p[loc1.x][loc1.y - 1] == 'O' || p[loc1.x][loc1.y - 1] == '*')
			state = 1; // indicate the end of the game
		else
		{
    
    
			if (p[loc1.x][loc1.y - 1] == '#')
			{
    
    
				score++;
				snake.push_front(loc1);
			}
			else
			{
    
    
				p[snake.back().x][snake.back().y] = ' '; // delete the end of the tail
				snake.pop_back();
				snake.push_front(loc1); // former head -> front of the tail
			}
		}
		--loc1.y;
		break;
	case 4: // right
		if (p[loc1.x][loc1.y + 1] == 'O' || p[loc1.x][loc1.y + 1] == '*')
			state = 1; // indicate the end of the game
		else
		{
    
    
			if (p[loc1.x][loc1.y + 1] == '#')
			{
    
    
				score++;
				snake.push_front(loc1);
			}
			else
			{
    
    
				p[snake.back().x][snake.back().y] = ' '; // delete the end of the tail
				snake.pop_back();
				snake.push_front(loc1); // former head -> front of the tail
			}
		}
		++loc1.y;
		break;
	default: //others
		break;
	}
	for (auto c : snake)
		p[c.x][c.y] = 'O'; // print the tail
	p[loc1.x][loc1.y] = '@'; // print the head
}

int main()
{
    
    
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_CURSOR_INFO cci;
	GetConsoleCursorInfo(hOut, &cci);
	cci.bVisible = FALSE;
	SetConsoleCursorInfo(hOut, &cci);
	// The five lines above are used to hide the Console Cursor.
	char c1 = '\0', c2 = '\0';
	int time_set;
	std::cout << "This is a simple snake game.\nProgrammer:Teddy van Jerry" << endl;
	Sleep(300);
	std::cout << "\nNow Loading";
	for (int i = 0; i != 6; i++)
	{
    
    
		Sleep(200);
		std::cout << ".";
	}
	Sleep(500); // stop for a while
	std::cout << "\n\nYou can move the snake using ↑,↓,←,→." << endl;
	std::cout << "\nYou can choose the speed the snake moves.\nVery slow(1) Slow(2) Medium(3) Fast(4) Very Fast(5) Very Very Fast(6)" << endl;
	char choice;
	choice = _getch();
	switch (choice) // set the speed
	{
    
    
	case '1':
		time_set = 1000;
		break;
	case '2':
		time_set = 700;
		break;
	case '3':
		time_set = 500;
		break;
	case '4':
		time_set = 350;
		break;
	case '5':
		time_set = 250;
		break;
	case '6':
		time_set = 150;
		break;
	default:
		time_set = 500;
		break;
	}
	p_def(); // define p
	cout << "\nNow get ready!\n" << endl;
	Sleep(3500);
	ran();
	while (state == 0)
	{
    
    
		unsigned long clock_p = clock();
		print();
		std::cout << "\nYour current score is " << score << " .\n" << endl;
		do
		{
    
    
			if (_kbhit()) // test if there is a click on the button
				input(c1, c2);
		} while (clock() - clock_p < time_set);
		move();
		if (p[(vec[cnt]).x][(vec[cnt]).y] == ' ')
			p[(vec[cnt]).x][(vec[cnt]).y] = '#'; // generate food for the snake to eat
		cnt++;
	}
	std::cout << "\nThe game is over.\nYour final score is " << score << " !" << endl;
	std::cout << "\nALL RIGHTS RESERVED (c) 2020 Teddy van Jerry" << endl;
	char anything;
	cin >> anything;
	return 0;
}

// ALL RIGHTS RESERVED (c) 2020 Teddy van Jerry

Exemple de sortie

Production
(Certaines lacunes sont que le programme clignotera un peu, ce n'est pas possible)

une analyse

  • J'ai écrit beaucoup de questions au début, et il a fallu beaucoup de temps pour trouver des bogues.
    F1
    Puis c'est arrivé à nouveau (Pourquoi est-ce que toute la tête et le corps ont été coupés?) Et F2
    puis c'est arrivé à nouveau
    F3
  • Peut regarder la fonction du temps de traitement, il est dans la bibliothèque ctimedans la time()fonction, en millisecondes, la sortie réelle est longue.
  • Sleep()C'est la bibliothèque Windows.hoù la fonction est suspendue tant de millisecondes.
  • Le comportement 192-196 annule le code du curseur, trouvé en ligne.
  • La ligne 248 _kbhit()est entrée détermine si oui ou non l'entrée clavier. Ici, l'utilisation _getch()n'est d'aucune utilité (ces deux fonctions de la bibliothèque sont là conio.h), j'ai essayé celle-ci avant tant de mauvaises raisons. Il s'avère que le programme restera bloqué dans l'entrée sans jugement et qu'il ne bougera pas si vous ne le saisissez pas.
  • Concernant la saisie des touches fléchées, veuillez vous référer à mon blog [Programme C ++] Application et analyse dans le jeu Mobile Maze .
  • Le rangement de la queue de serpent est à l'intérieur, l' dequeavantage est que les deux extrémités sont utilisables et que la sortie est pratique. Une utilisation spécifique peut être recherchée sur le RSCF.
  • Le script 258-259 n'a pas de sens, le but est d'utiliser le fichier exe seul, parfois lorsque le jeu se termine, il se fermera directement sans afficher le résultat final. Ajoutez cette phrase inutile pour le résoudre. Voir mon blog penser au programme C ++ fonctionnant sur d'autres appareils .
  • Pour la fonction de position aléatoire personnalisée, ran()veuillez consulter mon blog [Programme C ++] Random Number .
  • Voir mes fonctions définies par mon blog sur l'impact des définitions de fonction de la pensée en C ++ .

TOUS DROITS RÉSERVÉS © 2020 Teddy van Jerry
Bienvenue à réimprimer, veuillez indiquer la source.


Voir également

Page de navigation de Teddy van Jerry
[programme C ++] Jeu Gobang (humain VS humain)
[programme C ++] Jeu Tic-Tac-Toe (humain VS humain)
[programme C ++] Jeu Tic-Tac-Toe (ordinateur VS humain Lv1)
[programme C ++] Tic Tac Toe Jeu d'échecs (Ordinateur humain VS Lv2)
[Programme C ++] Jeu Tic-Tac-Toe (Ordinateur humain VS Lv3)
[Programme C ++] Jeu Tic-Tac-Toe (Ordinateur humain VS Lv3) (Version statistique)
[Programme C ++] Jeu de labyrinthe mobile
[C ++ Programme] Nombre aléatoire
[programme C ++] Jeu de société push numérique (15-puzzle)
[programme C ++] Jeu 2048
[ programme C ++] Jeu Tic-Tac-Toe (humain VS humain) (interface graphique EasyX)
[programme C ++] Jeu Tic-Tac-Toe ( Ordinateur humain VS Lv3) (Record Statistics Edition) (EasyX Graphical Interface)

Je suppose que tu aimes

Origine blog.csdn.net/weixin_50012998/article/details/108423053
conseillé
Classement