[Programa C ++] Juego de placa de empuje digital (15 rompecabezas)

Creo que este juego es una prueba de contenido de pensamiento, después de todo, está en el escenario del cerebro más poderoso.
Sin embargo, escribir este programa también es agotador (principalmente hay un gran error que no se encuentra, vea el análisis más adelante).

programa

//This is a simple 15-puzzle game.

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

int sx = 3, sy = 3; // int connot be replaced by unsigned

vector<vector<char>> p = {
    
    
	{
    
    '1','2','3','4'},
	{
    
    '5','6','7','8'},
	{
    
    '9','A','B','C'},
    {
    
    'D','E','F',' '}};

vector<vector<char>> p0 = p; // the finished state

void change(int n)
{
    
    
	switch (n)
	{
    
    
	case 1: // up
		if (sx + 1 <= 3)
		{
    
    
			p[sx][sy] = p[sx + 1][sy];
			p[sx + 1][sy] = ' ';
			++sx;
		}
		break;
	case 2: // down
		if (sx - 1 >= 0)
		{
    
    
			p[sx][sy] =  p[sx - 1][sy];

			p[sx - 1][sy] = ' ';
			--sx;
		}
		break;
	case 3: // left
		if (sy + 1 <= 3)
		{
    
    
			p[sx][sy] = p[sx][sy + 1];
			p[sx][sy + 1] = ' ';
			++sy;
		}
		break;
	case 4: // right
		if (sy - 1 >= 0)
		{
    
    
			p[sx][sy] = p[sx][sy - 1];
			p[sx][sy - 1] = ' ';
			--sy;
		}
		break;
	default:
		break;
	}
}

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

void random_start() // create a random plate
{
    
    	
	default_random_engine random;
	vector<int> ivec;
	for (int i = 0; i != 400; i++)
		ivec.push_back(random() % 4 + 1);
	srand((unsigned)time(NULL));
	int ran = rand() % 200; // generate a random number ranging from 0 to 199
	for (int i = ran; i != ran + 200; i++) // make 200 moves
		change(ivec[i]);
	if (sx == 0) change(1);
	if (sx == 1) change(1);
	if (sx == 2) change(1);
	if (sy == 0) change(3);
	if (sy == 1) change(3);
	if (sy == 2) change(3); // move the empty place to p[3][3]
}

void print(vector<vector<char>> q)
{
    
    
	for (int i = 0; i != 4; i++)
	{
    
    
		for (int j = 0; j != 4; j++)
			cout << "|" << q[i][j];
		cout << "|" << endl;
	}
}

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.	
	cout << "This is a simple 15-puzzle game.\nProgrammer:Teddy van Jerry" << endl;
	random_start();
	cout << "\nYou can move the number ranging from 1 to F using ↑,↓,←,→.\n" << endl;
	print(p);
	cout << "\nNow you have 10 seconds to get ready. After that, we will begin.\n" << endl;
	for (int i = 10; i != 0; i--)
	{
    
    
		cout << i;
		Sleep(1000); // wait for a second;
		cout << " ";
	}
	cout << "Go!\n" << endl;
	long time_start = clock(); // the starting point
	unsigned cnt = 0;
	while (p != p0) // when it's unfinshed
	{
    
    
		char a1 = '\0', a2 = '\0';
		input(a1, a2);
		print(p);
		cout << "\n" << endl;
		++cnt;
	}
	long total_time = clock() - time_start;
	int min = total_time / 60000;
	int second = (total_time % 60000) / 1000;
	string zero = (second < 10) ? "0" : "";
	cout << "You made it!" << endl;
	cout << "You made " << cnt << " moves. ";
	cout << "The total time is " << min << "'" << zero << second << "\"." << endl;
	cout << "\nALL RIGHTS RESERVED (c) 2020 Teddy van Jerry" << endl;
	char anything;
	cin >> anything;
	return 0;
}

//Copyright :2020 Teddy van Jerry

Salida de muestra

1
2

análisis

  • ¡Déjame hablar primero sobre el error más problemático! El siguiente error ha sido:
    insecto

Luego descubrí que el problema estaba en la move()función. Después de mucho tiempo, descubrí que move()estaba sobrecargado y el cambio change()seguía siendo incorrecto. Trabajé en él durante mucho tiempo (más de dos horas en total). Después de considerar varias situaciones, no sabía cuánto después de revisarlo. Una y otra vez, de repente descubrí que todo fue unsignedcausado. Aunque las coordenadas de la vacante no pueden ser negativas, pero change()para determinar si hay una función legítima de la entrada cuando está en -1funcionamiento (de hecho, se movió a la derecha a la derecha) porque unsignedcon el 0tiempo -1se volverá redonda es un valor muy grande , El juicio debe establecerse, por lo que habrá vector subscript out of range.

  • Tenga en cuenta que la salida de la línea 151 "debe utilizar caracteres de escape \.
  • Otros problemas son similares a los del juego de la serpiente .

TODOS LOS DERECHOS RESERVADOS © 2020 Teddy van Jerry
bienvenido a reimprimir, por favor indique la fuente.


Ver también

Página de navegación de Teddy van Jerry
[Programa C ++] Juego Tic-Tac-Toe (Humano VS Humano)
[Programa C ++] Juego Tic-Tac-Toe (Computadora Human VS Lv1)
[Programa C ++] Juego Tic-Tac-Toe (Computadora Human VS Lv2)
[Programa C ++ 】 Juego Tic-Tac-Toe (Computadora humana VS Lv3)
[Programa C ++] Juego Tic-Tac-Toe (Computadora humana VS Lv3) (Edición de estadísticas)
[Programa C ++] Juego Gobang (Humano VS humano)
[Programa C ++] Juego de laberinto en movimiento
[C ++ Programa] Número aleatorio
[Programa C ++] Juego Snake
[Programa C ++] Juego 2048
[ Programa C ++] Juego Tic-tac-toe (humano VS humano) (Interfaz gráfica EasyX) [Programa C ++] Juego Tic -tac-toe
(humano VS computadora Lv3) (Versión de estadísticas de registro) (Interfaz gráfica EasyX)


¿Ha encontrado algún error en la imagen? Esto es en realidad en Snake Game , pero lo cambié con 3D Paint .

Supongo que te gusta

Origin blog.csdn.net/weixin_50012998/article/details/108446155
Recomendado
Clasificación