Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <conio.h>
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <time.h>
- #include <windows.h>
- using namespace std;
- int map[10]={0}; //一開始10格都設為0 ,但是捨棄第0格,只用map[1]~map[9]九宮格
- vector<string> bign{"0","1","2","3","4","5","6","7","8","9"}; //用來輸出的全形數字,因為空白格 □是全形,這樣格子才不會歪掉
- int p;//目前位置
- int k;//目前按鍵
- int s;//目前移動數
- string puzzle=" 153247860";//範例測資
- //第一題,初始化,把範例測資安排到對應的格子裡
- void init() {
- cin>>puzzle;
- puzzle = " " + puzzle;
- int i;
- for( i = 1 ; i <=9 ; i++ ){
- map[i] = puzzle[i] - '0';
- if( puzzle[i] == '0' ){
- p = i;
- }
- }
- s = 0;
- }
- //第一題,九宮格繪製,0用白色方塊顯示,其餘用全形數字
- void draw() {
- system("cls"); //cls means clear screen
- cout << "steps:" << s << endl;
- for(int i = 1 ; i <= 9 ; i++ ){
- if( map[i] == 0 ){
- cout << "□";
- }
- else{
- cout << bign[ map[i] ];
- }
- if( i % 3 == 0 ){
- cout << endl;
- }
- }
- }
- int main(void)
- {
- init();
- draw();
- while(1){
- if( kbhit() ){
- k = _getch();
- if(k == 'q'){
- break;
- }
- else if( k == 'e'){
- if( p < 7 ){
- int x = p + 3 ;
- int y = map[x];
- map[x] = map[p];
- map[p] = y;
- p = x;
- }
- }
- else if( k == 'd'){
- if( p > 3 ){
- int x = p - 3 ;
- int y = map[x];
- map[x] = map[p];
- map[p] = y;
- p = x;
- }
- }
- else if( k == 's'){
- if( p % 3 != 0 ){
- int x = p + 1 ;
- int y = map[x];
- map[x] = map[p];
- map[p] = y;
- p = x;
- }
- }
- else if( k == 'f'){
- if( p % 3 != 1 ){
- int x = p - 1 ;
- int y = map[x];
- map[x] = map[p];
- map[p] = y;
- p = x;
- }
- }
- if( k == 'e' || k == 'd' || k == 's' || k == 'f' ){
- s++;
- }
- bool finished = true;
- for( int i = 1 ; i <= 8 ; i++ ){
- if( map[i] != i ){
- finished = false;
- break;
- }
- }
- if( finished ){
- draw();
- cout<<"you win!\n";
- break;
- }
- draw();
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment