Skip to content

Instantly share code, notes, and snippets.

@ustreamer-01647
Created September 23, 2012 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ustreamer-01647/3769584 to your computer and use it in GitHub Desktop.
Save ustreamer-01647/3769584 to your computer and use it in GitHub Desktop.
マルバツゲーム
#include <iostream>
#include <set>
#include <vector>
void showBoard( const std::vector<char> Stones, const int Size )
{
for ( int i = 0; i < Size; i++ )
{
for ( int j = 0; j < Size; j++ )
{
std::cout << Stones[ j + i * Size ];
std::cout << "|";
}
std::cout << std::endl;
std::cout << "------" << std::endl;
}
}
void initStones( std::vector<char> &stones, const int Size )
{
for ( int i = Size*Size; i > 0; i-- )
{
stones.push_back ( '0' + i );
}
}
/** 石を置く.
画面表示は9-1なので,アクセスは Size*Size-position
@return 成立したらtrue.そうでなければfalse
*/
bool setStone ( std::vector<char> &stones, const int Size, const int position, const char player )
{
if ( stones[Size*Size-position] > '9' )
{
// 既に石を置いている.
return false;
}
stones[Size*Size-position] = player;
return true;
}
int main( void )
{
// 盤の大きさ
const int BoardSize = 3;
// 石とその初期化
std::vector<char> stones;
initStones ( stones, BoardSize );
// プレイヤーの石
const std::pair<char, char> PlayerStone( 'o', 'x' );
// ゲーム本編
// 手
int move = 1;
// 石設置位置
int position;
while( move <= BoardSize * BoardSize )
{
// 盤面表示
showBoard( stones, BoardSize );
// 石設置入力待ち
std::cin >> position;
// 設置位置確認
if ( position <= 0 || position > BoardSize * BoardSize )
{
std::cout << "置けない" << std::endl;
std::cin.clear();
std::cin.ignore();
continue;
}
// 石設置確認
bool result;
// プレイヤー確認
if ( move % 2 == 1 )
{
// 先手
result = setStone( stones, BoardSize, position, PlayerStone.first );
}else
{
// 後手
result = setStone( stones, BoardSize, position, PlayerStone.second );
}
if ( result == true )
{
// 手を進める
move++;
}else
{
std::cout << "置けない" << std::endl;
}
}
showBoard ( stones, BoardSize );
std::cout << "game over" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment