Beispiel #1
0
/**
 * @brief  main 
 *
 * @param  argc
 * @param  argv[]
 *
 * @return  
 */
int main ( int argc, char *argv[] ) { 
	char board[N][N] = { {0,0} };
//	int *player = &Player;
	int x = 0, y =0;
	int flag = 2;
	status s = -1;
	CreateBoard(board);
	while ( true ) {
		PrintBoard(board, x, y);
		PrintInfo(flag, Player);
		if ( s == WIN ) {
			printf ( "\033[33mSome one win!\n\033[0m" );
			break;
		}
		s = PlayChess(board, Player, &x, &y);
		if ( s == -1 ) continue;
		if ( s == RES ) {
			printf ( "Someone rescinded!\n" );
		}
		if ( s == QUIT ) {
			printf ( "Gave Over\n" );
			break;
		}
		s =  CheckBoard(board, Player, &x,&y);
		Player = ( Player + 1 ) % 2;

	}
	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
Beispiel #2
0
      /**
       * A Gomoku constructor takes a board object and a label to update
       * with instructions, and then initializes the state of the board
       **/
      explicit Gomoku() :
          game_state_(PLAYER_ONE_TURN), turn_number_(0), player_(PLAYER_ONE) {
        // Game specific data
        INITIAL_DIRECTIVE = "Player 1 Make Your Move...";
        DRAW_DIRECTIVE = "It's A Tie! Neither Player Wins";
        PLAYER_NAME[PLAYER_ONE] = "Player 1";
        PLAYER_NAME[PLAYER_TWO] = "Player 2";
        PLAYER_COLOR[PLAYER_ONE] = "#000";
        PLAYER_COLOR[PLAYER_TWO] = "#FFF";
        PLAYER_DIRECTIVE[PLAYER_ONE_TURN] =
          PLAYER_DIRECTIVE[PLAYER_TWO_TURN] = " Take Your Turn";
        PLAYER_DIRECTIVE[GAME_OVER] = " Won the Game!";
        PLAYER_DIRECTIVE[RESETTING] = "Resetting the Board...";

        // Initialize game components
        CreateHeader();
        CreateBoard();
        CreateMenu();

        // Initialize game board and state
        board_state_ = new Player*[board_->height()];
        for (int i = 0; i < board_->height(); i++) {
          board_state_[i] = new Player[board_->width()];
          for (int j = 0; j < board_->width(); j++)
            board_state_[i][j] = NEITHER;
        }
      }
Beispiel #3
0
void MainWindow::InitSpace()
{
    QFile file("spaces.txt");
    QString fileContent;
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        fileContent = file.readAll();
        file.close();
    }
    else
    {
        QMessageBox::critical(this,"Error","Can't load the space file.");
        exit(1);
    }
    QStringList lines = fileContent.split("\n");
    if(lines.size() < 80)
    {
        QMessageBox::critical(this,"Error","The space file is incorect.");
        exit(1);
    }
    for(int i = 0; i < 80; i += 2)
    {
        Space* s = new Space();
        s->setSpace(lines[i],lines[i + 1]);
        spaces.append(s);
    }
    CreateBoard();
}
Beispiel #4
0
void record_R() {
    struct Record r[10];
    int i;
    char ip = '\0';
    FILE *f;
    f = fopen("record.txt", "r");

    for (i = 0; i<10; i++)
        fscanf(f, "%s %d\n", r[i].name, &r[i].Level);
    fclose(f);

    printf("이름   점수\n");
    printf("------------------\n");
    for (i = 0; i<10; i++)
        printf("%s %d\n", r[i].name, r[i].Level);

    ip = _getch();

    if (ip == ESC)exit(0);
    else {
        system("cls");
        ConsoleInit();
        DrawField();
        CreateBoard();
        StartGame();
    }
}
Beispiel #5
0
Board::Board()
{
	CreateBoard();
	m_checkerSelected = new BoardPiece();
	m_blueTurn = false;
	m_prevMoveColorWasBlack = false;
	m_foundEatenChecker = false;
}
Beispiel #6
0
int main() {
    ConsoleInit();
    DrawField();
    CreateBoard();
    StartGame();

    SetCursors(0, 0);
}
void Simple_Game_Board::SetupBoard(void)
{
	if (m_arrBoard == NULL) //Create the Board if needed
		CreateBoard();

	for (int row = 0; row < m_nColumns; row++) //Randomly set each square to a color
		for (int col; col < m_nColumns; col++)
			m_arrBoard[row][col] = (rand() % 3) + 1;
}
Beispiel #8
0
main()
{
	Dudes *Board[8][8];
	CreateBoard(Board);
	SetupBoard(Board);
	while (1)
	{
		TakeTurn(Board);
	}
}
void SameGameBoard::SetupBoard(void)
{
	// Create board, if needed
	if(m_arrBoard == NULL)
		CreateBoard();
	// Randomly set spaces to colors
	for(int row = 0; row < m_nRows; row++)
		for(int col = 0; col < m_nColumns; col++)
			m_arrBoard[row][col] = (rand() % 3) + 1;
	// Set remaining blocks
	m_nRemaining = m_nRows * m_nColumns;
}
Beispiel #10
0
//TODO : 探索深さを、2以上に変更
int CpuTurn(info_board *current_board, int color) {
    int y, x;
    info_board next_board;
    move_s move, best_move = { -1, -1 };
    int score = -9999999, tmp;

    CreateBoard(&next_board, current_board);

    //最善手探索
    for (y = 0; y < GRID; y++) {
        for (x = 0; x < GRID; x++) {
            move.y = y;
            move.x = x;
            if (PutBoard(&next_board, &move, color)) {
                tmp = calc_evaluationvalue(&next_board, &move, color);
                if (score < tmp) {
                    best_move.y = y;
                    best_move.x = x;
                    score = tmp;
                }
                DelBoard(&next_board);
                CreateBoard(&next_board, current_board);
            }
        }
    }

    if (best_move.y == -1 || best_move.x == -1) {
        printf("CPU pass:\n");
        return 1;
    }

    printf("CPU is [%c][%d]\n", best_move.x + 'a', best_move.y + 1);
    PutBoard(current_board, &best_move, color);
    DelBoard(&next_board);

    return 0;
}
Beispiel #11
0
void FieldSystem::Start()
{
	m_eventManager->RegisterListener<MousePositionEvent>(this);
	m_eventManager->RegisterListener<MouseClickEvent>(this);
	m_eventManager->RegisterListener<KeyEvent>(this);
	m_eventManager->RegisterListener<PathFinishedEvent>(this);
	m_eventManager->RegisterListener<RecalculateFieldEvent>(this);

	m_transformComponents = m_dataModel->getComponents<TransformComponent>();
	m_fieldComponents = m_dataModel->getComponents<FieldComponent>();
	m_spriteComponents = m_dataModel->getComponents<SpriteComponent>();

	CreateBoard();
	m_eventManager->QueueEvent<ShowMessageEvent>(new ShowMessageEvent("Please choose a starting point."));
}
Beispiel #12
0
Game* CreateGame(int rows, int cols)
{   Game* game = malloc(sizeof(Game));
    if(game)
    {   game->win_level = 11;
        game->random_max_level = 2;
        game->random_seed = 0;
        game->random = 0;
        game->score = 0;
        game->status = GAME_STATUS_NEW;
        game->board = CreateBoard(4, 4);
        if(game->board == NULL)
        {   free(game);
            game = NULL;
        }
    }
    return game;
}
Beispiel #13
0
void Play(tGame * game)
{	
	int legal;

	tScan scan;
	tCommand command;
	command.undo.can_undo = FALSE;
	command.undo.undo_error = FALSE;
	command.undo.lastboard.rows = game->visualboard.rows; 
	command.undo.lastboard.columns = game->visualboard.columns;
	CreateBoard(&command.undo.lastboard);;

	do
	{
		PrintAll(game, &command);
		
		do
		{	
			if ((legal = InputCommand(&scan)))
			{	
				if((legal = LegalCommand(&scan, &command)))
					if (command.command_ref < 5) /*All commands but quit or undo*/
						legal = LegalParams(game, &command, &scan);
			}

		if (!legal)
			printf("%s%s%s\n", KERR, COMMAND_ERR, KDEF);

		} while (!legal);

		ExecCommand(game, &command);
		CheckGameState(game);
	} while(game->gamestate == GAMESTATE_DEFAULT);

	PrintResult(game);

	freeBoard(game->hiddenboard.board, game->hiddenboard.rows);
	freeBoard(game->visualboard.board, game->hiddenboard.rows);
	return;
}
Beispiel #14
0
void TestFace( BOARD *p_board, POINT pt, int msg )
{
    if( p_board->status == PLAYING || p_board->status == WAITING ) {
        if( msg == WM_LBUTTONDOWN || msg == WM_MBUTTONDOWN )
            p_board->face_bmp = OOH_BMP;
        else p_board->face_bmp = SMILE_BMP;
    }
    else if( p_board->status == GAMEOVER )
        p_board->face_bmp = DEAD_BMP;
    else if( p_board->status == WON )
            p_board->face_bmp = COOL_BMP;

    if( PtInRect( &p_board->face_rect, pt ) ) {
        if( msg == WM_LBUTTONDOWN )
            p_board->face_bmp = SPRESS_BMP;

        if( msg == WM_LBUTTONUP )
            CreateBoard( p_board );
    }

    RedrawWindow( p_board->hWnd, &p_board->face_rect, 0,
        RDW_INVALIDATE | RDW_UPDATENOW );
}
void InitNx()
{
    // Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);	
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_AXES, 1);

	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_POINT, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_NORMAL, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	NxU32 set = 0;

#ifdef WIN32
	set = SetCurrentDirectory(&fname[0]);
	if (!set) set = SetCurrentDirectory(&fname1[0]);
	if (!set)
	{
		char basePath[256];
		GetModuleFileName(NULL, basePath, 256);
		char* pTmp = strrchr(basePath, '\\');
		basePath[pTmp-basePath+1] = 0;
		SetCurrentDirectory(basePath);//for running from start menu

		set = SetCurrentDirectory(&fname2[0]);
	}
	if (!set) set = SetCurrentDirectory(&fname3[0]);
#elif LINUX
	set = chdir(&fname[0]);
	if (set != 0) set = chdir(&fname2[0]);
	if (set != 0) set = chdir(&fname3[0]);
#endif

	// Create the default material
	NxMaterialDesc defaultMaterial;
	defaultMaterial.restitution		= 0;
	defaultMaterial.staticFriction	= 0.5;
	defaultMaterial.dynamicFriction	= 0.5;
	NxMaterial* m = gScene->getMaterialFromIndex(0);
	m->loadFromDesc(defaultMaterial);

	// Load the ramp scene
	char buffer[512];
	FindMediaFile("Ramp.pml", buffer);
	nxmlLoadScene(buffer, gPhysicsSDK, gScene);

	// Switch from Max Coordinate System to
	// Training Program Coordinate System
	NxMat34 mat;
    NxMat33 orient;
	orient.setColumn(0, NxVec3(-1,0,0));
	orient.setColumn(1, NxVec3(0,0,1));
	orient.setColumn(2, NxVec3(0,1,0));
	mat.M = orient;
	SwitchCoordinateSystem(gScene, mat);

	// Reset wheel material
	wsm = NULL;

	// Create board actor
	board = CreateBoard(NxVec3(0,3,0));
	board->wakeUp(1e30);

    AddUserDataToActors(gScene);

	gSelectedActor = board;

	// Initialize HUD
	InitializeHUD();
	InitializeSpecialHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Beispiel #16
0
int main()
{
	LoadDict(&M);
    	system("clear");
    	printf("%s=====================================================================\n", cyan);
    	printf(" _       ______  ____  ____  ___    __  __________   ________   ____ \n");
    	printf("| |     / / __ \\/ __ \\/ __ \\/   |  /  |/  / ____/ | / /_  __/  / __ \\ \n");
    	printf("| | /| / / / / / /_/ / / / / /| | / /|_/ / __/ /  |/ / / /    / / / /\n");
    	printf("| |/ |/ / /_/ / _ _ / /_/ / ___ |/ /  / / /___/ /|  / / /    / /_/ / \n");
    	printf("|__/|__/\\____/_/ |_/_____/_/  |_/_/  /_/_____/_/ |_/ /_/     \\____/  \n\n");
    	printf("=====================================================================\n\n\n");
    	printf("                      %sPress any key to continue%s\n",magenta,normal);
    	getch();
   	while(opt1 != 5)  //OPT1 = 5 adalah QUIT
	{
        MainMenu(&opt1);       // MENAMPILKAN MAIN MENU
        switch(opt1)
        {
            case 1 : 	// REGISTER
                printf("%sEnter user name : ", cyan);

                do
                {
                    found = false;	// INISIALISASI YANG MENANDAKAN USER BELUM DITEMUKAN DI FILE EKSTERNAL
                    scanf("%s", username.TabKata);
                    username.Length = strlen(username.TabKata); 
                    if(strlen(username.TabKata) >= 20 || !(IsAlNumS(username))) // MENGECEK APAKAH LEBIH DARI 20 ATAU ALFANUMERIK
                        printf("Username must be alphanumeric / less or equal to 20 characters\n");
                    else
                    {
                        *x = "scores/List Users & Highscores 2.txt";
                        STARTKATA();
                        while(!EndKata && !found)
                            CheckUser(username,&id,&found);

                        if(found)
                            printf("Sorry, that username already exists\n");
                    }
                }while((strlen(username.TabKata) >= 20 || !(IsAlNumS(username))) || found);
		
                SalinFile(LU,username);
                printf("Congratulations! %s has been successfully registered\n",username.TabKata);
                printf("\n");
                printf("%sPress any key to continue%s\n", magenta,cyan);
                dummygetch = getch();
		dummygetch = getch();
                break;

            case 2 :	//LOGIN			
                CreateList(&LU);
                printf("\n");
                *x = "scores/List Users & Highscores 2.txt";
                STARTKATA();
                while(!(EndKata))
                    InitUser(&LU,&id);	// MEMASUKKAN DATA FILE EKSTERNAL KE DALAM LIST
                InversListU(&LU);
                ListUsersLengkap(LU);	// MENAMPILKAN LIST USER
                found1 = false;		// INISIALISASI YANG MENANDAKAN USERNAME TIDAK DITEMUKAN
                while(!found1)
                {
                    printf("=====================================================================\n");
                    printf("Enter username : "******"%s",username1.TabKata);
                    username1.Length = strlen(username1.TabKata);
                    STARTKATA();
                    while(!EndKata && !found1)
                        CheckUser(username1,&id,&found1);

                    if(!found1)
                        printf("%s not found. Try again\n",username1.TabKata);
                }

                SelectB = true;	// INISIALISASI AGAR SETELAH MEMILIH BOARD, MELIHAT SCORE TIDAK KELUAR KE MAIN MENU, MELAINKAN PREP MENU
                selectT = false;	// INISIALISASI YANG MENANDAKAN USER BELUM PILIH BOARD
                
                while(SelectB == true)
                {
		    if(selectT == false)
			kode = 1;

                    PrepMenu(&opt2, username1);	// PREPARATION MENU
                    switch(opt2)
                    {
                        case 1 :	// PLAY GAME
                            if(selectT == false) 
			    {
                                kode = 1;
                                *y = "boards/1.txt";
                            }
                            baris = 1;
                            kolom = 1;
                            T = false;
                            used = false;
                            score = 0;
                            CreateEmptyQ(&QFinish);
                            CreateEmpty(&S);
							CreateListSU(&LSG);
							CreateListSU(&LSGTemp);
							
							ReadSuggestion(&LSG, kode);
							strcpy(tempsugg, username1.TabKata);
							PSU = FirstSU(LSG);
							usersuggfound = false;
							while (PSU != Nil) {
								if (strcmp(InfoSU(PSU), tempsugg) == 0) {
									usersuggfound =  true;
									break;
								}
								else {
									PSU = NextSU(PSU);
								}
							}
							if (!usersuggfound) {
								InsVSUFirst(&LSG, tempsugg);
								PSU = FirstSU(LSG);
							}
							InsVSUFirst(&LSGTemp, tempsugg);
							PSE = FirstSE(PSU);
							if (PSE != Nil) 
								strcpy(tempsugg, InfoSE(PSE));
							else {
								tempsugg[0] = ' ';
								tempsugg[1] = '\0';
							}
							CreateListSet(&LS);
                            CreateBoard(&B);
                            AmbilBoard(&B);
                            InitKursor(&B);
                            InitSelect(&B, &S);
                            system("clear");
                            printf("Score = %d\n\n", score);
                            printf("Suggestion = %s\n\n", InfoSE(PSE));
                            TulisBoard(B);
                            printf("\n\n");
                            dummygetch = getch();
                            input = getch();
                            printf("\n");
                            while (input != 'm')
                            {
                                system("clear");
                                ProsesKursor(&B, &baris, &kolom, &T, input, &error);
                                Select(&B, baris, kolom, T, &S, &score, &LS, &QFinish, &used, &LSG, &LSGTemp, &M, PSU);
                                printf("Score = %d\n\n", score);
                                PSE = FirstSE(PSU);
                                printf("Suggestion = %s\n\n", InfoSE(PSE));
                                TulisBoard(B);
                                printf("\n");
                                if (used)
									printf("Invalid Word\n");
								else
									printf("\n");
                                if (error)
                                    printf("error\n");
                                else
                                    printf("\n");
                                input = getch();
                                printf("\n");
                                error = false;
                                used = false;
                            }
                            time(&rawtime);	//INISIALISASI WAKTU
			    t = localtime(&rawtime);
			    D.YY = (*t).tm_year+1900;
			    D.MM = (*t).tm_mon+1;
			    D.DD = (*t).tm_mday;
		            J.HH = (*t).tm_hour;
		  	    J.MM = (*t).tm_min;
			    J.SS = (*t).tm_sec;
                            InsSortScoreU (&LU,D,J,score,username1);	//INSERT SCORE KE LIST SCORE
                            SalinInto(LU, kode);	// MENYALIN KE FILE EKSTERNAL
                            SelectB = false;
                            system("clear");
                            addressQ PQ;
                            PQ = Head(QFinish);
                            while (PQ != Nil) 
			    {
			    	PrintSet(InfoQ(PQ));
				printf("\n");
				PQ = NextQ(PQ);
		       	    }
				printf("Total Score = %d\n", score);
							PSU = FirstSU(LSG);
							PSE = FirstSE(PSU);
							PSUT = FirstSU(LSGTemp);
							while (PSUT != Nil) {
								PSET = FirstSE(PSUT);
								while (PSET != Nil) {
									InsVSEFirst(&LSG, PSU, InfoSE(PSET));
									PSET = NextSE(PSET);
								}
								PSUT = NextSU(PSUT);
							}
							WriteSuggestion(LSG, kode);
							printf("Press any key to continue\n");
							dummygetch = getch();
			    getch();
                            break;

                        case 2 :	//SELECT BOARD
                            PilihBoard(&selectT, &kode);
		            CreateList(&LU);
			    STARTKATA();
                            while(!(EndKata))
                    	       InitUser(&LU,&id);	// MEMASUKKAN DATA FILE EKSTERNAL KE DALAM LIST
                	    InversListU(&LU);
                            SelectB = true;
                            break;

                        case 3 :	//VIEW MY HIGH SCORES
			    ViewMyHighScores(LU,username1);
			    printf("%sPress any key to continue%s\n", magenta,cyan);
			    dummygetch = getch();
			    dummygetch = getch();
                            SelectB = true;
  			    break;

                        case 4 :	//VIEW ALL HIGH SCORES	
			    ViewAllHighScores(LU);
	              	    printf("%sPress any key to continue%s\n", magenta,cyan);
			    dummygetch = getch();
			    dummygetch = getch();
                            SelectB = true;
                            break;

                        case 5 :	//VIEW BOARD STATISTICS	
 				CreateEmptyQS(&QS);
                            	countuser = 0;
				countscore = 0;
				sumscore = 0;
				PU = FirstU(LU);
				while (PU != Nil)
				{
					PS = FirstS(PU);
					if((InfoD(PS)).YY != 0)
					{
						countuser += 1;
					}	
					while(PS != Nil)
					{
						if((InfoD(PS)).YY != 0)
						{
							countscore += 1;
							sumscore += InfoS(PS);
						}	
						PS = NextS(PS);	
					}
					PU = NextU(PU); 	
				}
				//CreateList(&LU);
				averagescore = sumscore/countscore;
				printf("%.0f user/s have played in board %d\n",countuser,kode);
				if(countscore == 0)
					averagescore = 0;
				printf("The average score in board %d is %.2f\n",kode,averagescore);
				AddQS(&QS,kode,averagescore);
				for(i=0; i<=9;i++)
				{
					switch(i)
					{
						case 0 : *x = "scores/List Users & Highscores 1.txt"; break;
						case 1 : *x = "scores/List Users & Highscores 2.txt"; break;
						case 2 : *x = "scores/List Users & Highscores 3.txt"; break;
						case 3 : *x = "scores/List Users & Highscores 4.txt"; break;
						case 4 : *x = "scores/List Users & Highscores 5.txt"; break;
						case 5 : *x = "scores/List Users & Highscores 6.txt"; break;
						case 6 : *x = "scores/List Users & Highscores 7.txt"; break;
						case 7 : *x = "scores/List Users & Highscores 8.txt"; break;
						case 8 : *x = "scores/List Users & Highscores 9.txt"; break;
						case 9 : *x = "scores/List Users & Highscores 10.txt"; break;
					}
					if(i != kode)
					{
						CreateList(&LP);
						STARTKATA();
						while(!EndKata)
							InitUser(&LP,&id);
					
						InversListU(&LP);
						sumscore = 0;
						countscore = 0;
						PX = FirstU(LP);
						while (PX != Nil)
						{
							PZ = FirstS(PX);	
							while(PZ != Nil)
							{
								if((InfoD(PZ)).YY != 0)
								{
									countscore += 1;
									sumscore += InfoS(PZ);
								}	
								PZ = NextS(PZ);	
							}
							PX = NextU(PX); 	
						}
						if (countscore == 0)
							averagescore = 0;
						else
							averagescore = sumscore/countscore;
						AddQS(&QS, i, averagescore);
					}
							
				}
				PX = FirstU(LP);
				DealokasiU(&PX);
				PZ = FirstS(PX);
				DealokasiS(&PZ);
				P = Head(QS);
				printf("Difficulty Level of Boards : \n");
				for(i=1;i<=10;i++)
				{						
					printf("%d. Board no.%d with average user scores of %.2f\n",i,InfoQ(P),Prio(P));
					P = NextQ(P);
					if (P == Nil)
					{
						break;
					}
				}
			    printf("%sPress any key to continue%s\n", magenta,cyan);
           		    dummygetch = getch();
		  	    dummygetch = getch();
			    SelectB = true;
			    break;

                        case 6 :	// LOG OUT
                            SelectB = false;
                            break;
                    }
                if(SelectB == false)
                    break;
                }
		break;
            case 3 :	// HOW TO PLAY
		HowToPlay();
                break;
            case 4 :	// ABOUT
                About();
                break;
        }
	}
	printf("%s\n", normal); //MENGGANTI WARNA TEXT TERMINAL KE AWAL
	
	return 0;
}
Beispiel #17
0
LRESULT WINAPI MainProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;
    PAINTSTRUCT ps;
    HMENU hMenu;
    static BOARD board;

    switch( msg ) {
    case WM_CREATE:
        board.hInst = ((LPCREATESTRUCT) lParam)->hInstance;
        board.hWnd = hWnd;
        InitBoard( &board );
        CreateBoard( &board );
        return 0;

    case WM_PAINT:
      {
        HDC hMemDC;

        WINE_TRACE("WM_PAINT\n");
        hdc = BeginPaint( hWnd, &ps );
        hMemDC = CreateCompatibleDC( hdc );

        DrawBoard( hdc, hMemDC, &ps, &board );

        DeleteDC( hMemDC );
        EndPaint( hWnd, &ps );

        return 0;
      }

    case WM_MOVE:
        WINE_TRACE("WM_MOVE\n");
        board.pos.x = (short)LOWORD(lParam);
        board.pos.y = (short)HIWORD(lParam);
        return 0;

    case WM_DESTROY:
        SaveBoard( &board );
        DestroyBoard( &board );
        PostQuitMessage( 0 );
        return 0;

    case WM_TIMER:
        if( board.status == PLAYING ) {
            board.time++;
	    RedrawWindow( hWnd, &board.timer_rect, 0,
			  RDW_INVALIDATE | RDW_UPDATENOW );
        }
        return 0;

    case WM_LBUTTONDOWN:
        WINE_TRACE("WM_LBUTTONDOWN\n");
        if( wParam & MK_RBUTTON )
            msg = WM_MBUTTONDOWN;
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        SetCapture( hWnd );
        return 0;

    case WM_LBUTTONUP:
        WINE_TRACE("WM_LBUTTONUP\n");
        if( wParam & MK_RBUTTON )
            msg = WM_MBUTTONUP;
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        ReleaseCapture();
        return 0;

    case WM_RBUTTONDOWN:
        WINE_TRACE("WM_RBUTTONDOWN\n");
        if( wParam & MK_LBUTTON ) {
            board.press.x = 0;
            board.press.y = 0;
            msg = WM_MBUTTONDOWN;
        }
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        return 0;

    case WM_RBUTTONUP:
        WINE_TRACE("WM_RBUTTONUP\n");
        if( wParam & MK_LBUTTON )
            msg = WM_MBUTTONUP;
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        return 0;

    case WM_MBUTTONDOWN:
        WINE_TRACE("WM_MBUTTONDOWN\n");
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        return 0;

    case WM_MBUTTONUP:
        WINE_TRACE("WM_MBUTTONUP\n");
        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam), msg );
        return 0;

    case WM_MOUSEMOVE:
    {
        if( wParam & MK_MBUTTON ) {
            msg = WM_MBUTTONDOWN;
        }
        else if( wParam & MK_LBUTTON ) {
            msg = WM_LBUTTONDOWN;
        }
        else {
            return 0;
        }

        TestBoard( hWnd, &board, (short)LOWORD(lParam), (short)HIWORD(lParam),  msg );

        return 0;
    }

    case WM_COMMAND:
        switch(LOWORD(wParam)) {
        case IDM_NEW:
            CreateBoard( &board );
            return 0;

        case IDM_MARKQ:
            hMenu = GetMenu( hWnd );
            board.IsMarkQ = !board.IsMarkQ;
            if( board.IsMarkQ )
                CheckMenuItem( hMenu, IDM_MARKQ, MF_CHECKED );
            else
                CheckMenuItem( hMenu, IDM_MARKQ, MF_UNCHECKED );
            return 0;

        case IDM_BEGINNER:
            SetDifficulty( &board, BEGINNER );
            CreateBoard( &board );
            return 0;

        case IDM_ADVANCED:
            SetDifficulty( &board, ADVANCED );
            CreateBoard( &board );
            return 0;

        case IDM_EXPERT:
            SetDifficulty( &board, EXPERT );
            CreateBoard( &board );
            return 0;

        case IDM_CUSTOM:
            SetDifficulty( &board, CUSTOM );
            CreateBoard( &board );
            return 0;

        case IDM_EXIT:
            SendMessage( hWnd, WM_CLOSE, 0, 0);
            return 0;

        case IDM_TIMES:
            DialogBoxParam( board.hInst, "DLG_TIMES", hWnd,
                    TimesDlgProc, (LPARAM) &board);
            return 0;

        case IDM_ABOUT:
        {
            WCHAR appname[256], other[256];
            LoadStringW( board.hInst, IDS_APPNAME, appname, sizeof(appname)/sizeof(WCHAR) );
            LoadStringW( board.hInst, IDS_ABOUT, other, sizeof(other)/sizeof(WCHAR) );
            ShellAboutW( hWnd, appname, other,
                         LoadImageA( board.hInst, "WINEMINE", IMAGE_ICON, 48, 48, LR_SHARED ));
            return 0;
        }
        default:
            WINE_TRACE("Unknown WM_COMMAND command message received\n");
            break;
        }
    }
    return( DefWindowProc( hWnd, msg, wParam, lParam ));
}
Beispiel #18
0
void ConfirmBoard() {
    int i, j, n = 0;
    int tmp;
    char ip = '\0';
    for (i = 0; i<BOARD_HEIGHT; i++) {
        for (j = 0; j<BOARD_WIDTH; j++) {
            tmp = board[j][i];
            board[j][i] = board[j][i + 1];
            board[j][i + 1] = tmp;
            n += Bomb(i, j, 0);
            tmp = board[j][i];
            board[j][i] = board[j][i + 1];
            board[j][i + 1] = tmp;
        }
    }


    for (i = 0; i<BOARD_HEIGHT; i++) {
        for (j = 0; j<BOARD_WIDTH; j++) {
            tmp = board[j][i];
            board[j][i] = board[j + 1][i];
            board[j + 1][i] = tmp;
            n += Bomb(i, j, 0);
            tmp = board[j][i];
            board[j][i] = board[j + 1][i];
            board[j + 1][i] = tmp;

        }
    }
    if (TEST == T) {
        SetCursors(20, 23);
        printf("%d", n);
    }

    if (n < 2) {
        SetCursors(5, 20);
        printf("더 이상 게임진행이 어렵습니다.");
        SetCursors(5, 21);
        printf("게임을 계속하려면 space,그만둘려면 esc를 눌러주세요.");
        ip = _getch();
        switch (ip) {
        case ESC:
            system("cls");
            exit(1);
            break;
        case UP:
        case DOWN:
        case LEFT:
        case RIGHT:
        case SPACE: {
            SetCursors(5, 20);
            printf("                                                   ");
            SetCursors(5, 21);
            printf("                                                      \n");
            CreateBoard();
            StartGame();
            break;
        }
        }
    }
}
Beispiel #19
0
        //void deroulement_du_jeu()	
        int main(int argc, char *argv[] )
        {
            
            // if( !InitGUI() ){ return 0; }
            
            if( !CheckCommand(argc,argv) ){ return 0; }
            
            if( !InitLogFile() ){ printf("Fail init logFile\n"); }
            
            PrintHeaderMatch();
            
            //Il faut nbMaxCps pour chaques joueurs, donc on multiplie par 2
            nbMaxCps *= 2;
            
            if( !PrintLibInitHeader() ){ printf("Fail print libHeader\n"); }
            if( !LoadLibraries() ){ return(0); }
            PrintTLine();
            
            SGameState* gameState = CreateBoard();
            
            //Srand pour obtenir des nombres aléatoires 
            srand(time(NULL));

            //Initialisation des joueurs    
            j1InitLibrary(j1Name);   
            j2InitLibrary(j2Name);

            if( strlen(pathIA1) && !strlen(pathIA2) ){ PrintPhysicalPlayers(NULL,j2Name); }
            else if( !strlen(pathIA1) && strlen(pathIA2) ){ PrintPhysicalPlayers(j1Name,NULL); }
            else if( !strlen(pathIA1) && !strlen(pathIA2) ){ PrintPhysicalPlayers(j1Name,j2Name); }
            else { PrintPhysicalPlayers(NULL,NULL); }
            
            PrintIAPlayers(pathIA1,pathIA2);
            PrintMaxCps(nbMaxCps/2);
            
            j1StartMatch();
            j2StartMatch();

            int nbMatch = 3;
            int j1Win = 0;
            int j2Win = 0;

            while( nbMatch>0 && j1Win<2 && j2Win<2){

                PrintMatch(4-nbMatch);
                
                //   InitBoard
                
                //On initialise le nombre de coups maximums
                 int cptCps = nbMaxCps;
                 j1NbPenalty = 0;
                 j2NbPenalty = 0;
                 
                 InitGameState(gameState);
                 
                EPiece j1BoardInit[4][10];
                EPiece j2BoardInit[4][10];

                SetPlayerColors();
                
                j1StartGame(j1Color,j1BoardInit);
                j2StartGame(j2Color,j2BoardInit);

                if( j1Color == ECblue ){ PrintColors(j2Name, j1Name); }
                else{ PrintColors(j1Name, j2Name); }
                
                //Initialisation des pions sur le plateau
                if( j1Color == ECblue ){
                    if( !InitBlueBoard(gameState,j1BoardInit) ){PrintBoardInitError(ECblue);return 0;}           
                    if( !InitRedBoard(gameState,j2BoardInit) ){PrintBoardInitError(ECred);return 0;}
                }
                else{
                    if( !InitRedBoard(gameState,j1BoardInit) ){PrintBoardInitError(ECred);return 0;}
                    if( !InitBlueBoard(gameState,j2BoardInit) ){PrintBoardInitError(ECblue);return 0;}
                }

                //Le premier joueur est le rouge
                EColor player = ECred;

                EColor winner = 0;
                
                PrintLine();
                PrintGameState(gameState);
                
                while( !winner && cptCps>0 ){

                    SMove move;
                    
                    //Duplication du plateau
                    SGameState *gameStateCpy = (SGameState*) malloc(sizeof(SGameState));
                    GameStateCpy(gameState,gameStateCpy);
                    
                    //Si c'est le tour du joueur rouge, on inverse son plateau 
                    if( player == ECred ){
                        RevertGame(gameStateCpy);
                    }

                    //On cache les pions du joueur ennemi
                    HideColor(gameStateCpy,abs((player+1)%2)+2);
                    
                    if( player == j1Color ){ move = j1NextMove(gameStateCpy); }
                    else{ move = j2NextMove(gameStateCpy); }
                    
                    if( player == ECred ){
                        move.start.line = 9-move.start.line;
                        move.end.line = 9-move.end.line;
                    }
                    
                    int moveType = CorrectMove(gameState,move,player);

                    PrintMove(player,move);
                    
                    //Mouvement incorrecte
                    if( moveType == 0 ){
                        if( player == j1Color ){
                            j1NbPenalty++;
                            j1Penalty();
                            PrintInvalidMove(player,j1NbPenalty);
                            if( j1NbPenalty == 3 ){
                                PrintPenalty(j1Name,j1Color);
                                winner = abs((j1Color+1)%2)+2;
                                break;
                            }
                        }
                        else{ 
                            j2NbPenalty++;
                            j2Penalty(); 
                            PrintInvalidMove(player,j2NbPenalty);
                            if( j2NbPenalty == 3 ){
                                PrintPenalty(j2Name,j2Color);
                                winner = abs((j2Color+1)%2)+2;
                                break;
                            }
                        }
                    }
                    else{
                        //Attaque
                        if( moveType == 1 ){
                            EPiece army = gameState->board[move.start.line][move.start.col].piece;
                            EPiece enemy = gameState->board[move.end.line][move.end.col].piece;
                            if( player == j1Color ){
                                j1AttackResult(move.start,army,move.end,enemy);
                                j2AttackResult(move.end,enemy,move.start,army);
                            }
                            else{
                                j1AttackResult(move.end,enemy,move.start,army);
                                j2AttackResult(move.start,army,move.end,enemy);
                            }
                            
                            PrintAttackResult(player,move.start,army,move.end,enemy);
                        }
                        
                        ExecuteMove(gameState,move,player);
                    }
                    PrintGameState(gameState);

                    free(gameStateCpy);

                    if( player == ECred ){ player = ECblue; }
                    else{ player = ECred; }

                    winner = Finished(gameState);
                    cptCps--;
                }
                
                if( cptCps == 0){ PrintMaxMoveReached(); }
                else{ 
                    if( j1Color == winner ){ PrintMatchWinner(j1Name, winner, 4-nbMatch);j1Win++; }
                    else{ PrintMatchWinner(j2Name, winner, 4-nbMatch);j2Win++; }
                }
                nbMatch--;
                
                j1EndGame();
                j2EndGame();
                
                printf("j1Win : %d\nj2Win : %d\n",j1Win,j2Win);
            }
            if( j1Win >= 2 ){ PrintGameWinner(j1Name, j1Color); }
            else{ PrintGameWinner(j2Name, j2Color); }
            
            j1EndMatch();
            j2EndMatch();

            free(gameState);
            return(0);
        }