1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
#include <iostream>
#include <utility>
#include <algorithm>
#include <cctype>
constexpr int N = 5 ;
using grid_type = char[N][N] ;
enum direction { UP = 'w', DOWN = 's', LEFT = 'a', RIGHT = 'd', QUIT = 'q' };
using point = std::pair<int,int> ;
using std::swap ;
point locate( const grid_type& grid, char ch )
{
for( int row = 0 ; row < N ; ++row )
for( int col = 0 ; col < N ; ++col )
if( grid[row][col] == ch ) return { row, col } ;
return { -1, -1 } ; // not found
}
bool valid_loc( int x, int y ) { return x >= 0 && x < N && y >= 0 && y < N ; }
void move_up( grid_type& grid, char ch )
{
const auto [x,y] = locate( grid, ch ) ;
if( valid_loc( x, y ) && x > 0 ) swap( grid[x][y], grid[x-1][y] ) ;
}
void move_down( grid_type& grid, char ch )
{
const auto [x,y] = locate( grid, ch ) ;
if( valid_loc( x, y ) && x != (N-1) ) swap( grid[x][y], grid[x+1][y] ) ;
}
void move_left( grid_type& grid, char ch )
{
const auto [x,y] = locate( grid, ch ) ;
if( valid_loc( x, y ) && y != 0 ) swap( grid[x][y], grid[x][y-1] ) ;
}
void move_right( grid_type& grid, char ch )
{
const auto [x,y] = locate( grid, ch ) ;
if( valid_loc( x, y ) && y != (N-1) ) swap( grid[x][y], grid[x][y+1] ) ;
}
bool make_move( grid_type& grid, char ch ) // return false if the move is quit
{
char move ;
std::cout << "ener move (w/a/s/d/q): " ;
std::cin >> move ;
switch( std::tolower(move) )
{
case UP: move_up( grid, ch ) ; break ;
case DOWN: move_down( grid, ch ) ; break ;
case LEFT: move_left( grid, ch ) ; break ;
case RIGHT: move_right( grid, ch ) ; break ;
case QUIT: return false ;
default: ; // invalid move, ignored
}
return true ; // not quit
}
void print( const grid_type& grid )
{
for( const auto& row : grid )
{
for( char c : row ) std::cout << c << ' ' ;
std::cout << "\n\n" ;
}
}
int main()
{
const char star = '*' ;
grid_type tabla = { {'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X'},
{'X', 'X', star, 'X', 'X'},
{'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X'} };
do print(tabla) ; while( make_move( tabla, star ) ) ; // keep moving till user quits
}
|