• Предмет: Информатика
  • Автор: MSashaZ
  • Вопрос задан 4 месяца назад

С++

Створити гру п'ятнашки, налаштувати інтерфейс( вигляд гри, початок гри, кінець, поле гри). В кінці гри вивести на екран час гри і кількість перестановок.

Ответы

Ответ дал: flash77779
0

#include <iostream>

#include <ctime>

#include <cstdlib>

const int SIZE = 4;

int moves = 0;

time_t start, end;

int tiles[SIZE][SIZE];

// Функція для ініціалізації матриці плиток

void init() {

int n = 1;

for (int i = 0; i < SIZE; i++)

for (int j = 0; j < SIZE; j++)

tiles[i][j] = n++;

tiles[SIZE-1][SIZE-1] = 0;

}

// Функція для друку матриці плиток на екрані

void print() {

for (int i = 0; i < SIZE; i++) {

for (int j = 0; j < SIZE; j++) {

if (tiles[i][j] == 0) {

std::cout << " ";

} else {

std::cout << tiles[i][j] << ' ';

}

}

std::cout << std::endl;

}

}

// Функція для переміщення плиток

void move(int direction) {

int dx[] = {-1, 0, 1, 0};

int dy[] = {0, 1, 0, -1};

int x, y, nx, ny;

// Знаходимо пусту плитку

for (int i = 0; i < SIZE; i++) {

for (int j = 0; j < SIZE; j++) {

if (tiles[i][j] == 0) {

x = i;

y = j;

}

}

}

nx = x + dx[direction];

ny = y + dy[direction];

// Перевіряємо, чи переміщення в межах матриці

if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) {

std::swap(tiles[x][y], tiles[nx][ny]);

moves++;

}

}

// Функція для перевірки, чи виграшний стан

bool isWin() {

int n = 1;

for (int i = 0; i < SIZE; i++)

for (int j = 0; j < SIZE; j++) {

if (tiles[i][j] != n++)

return false;

}

return true;

}

int main() {

std::cout << "Game start!" << std::endl;

init();

start = time(0);

while (true) {

print();

int direction;

std::cin >> direction;

move(direction);

if (isWin()) {

end = time(0);

double time_taken = double(end - start);

std::cout << "Game over! You won in " << moves << " moves." << std::endl;

std::cout << "Time taken: " << time_taken << " seconds." << std::endl;

break;

}

}

return 0;

}

Вас заинтересует