Example #1
0
//! [2]
void xandos::select(int index, int player, bool send)
{
    if (0 > index || 8 < index) {
        qDebug() << "XandOs: invalid index ->" << index;
        return;
    }

    m_possibilities[index][8] = 1;
    for (int i = 0; i < 8; i++) {
        // Add the matrix at the selected index to the game matrix
        // multiply the matrix values based on player, if its user than
        // matrix row addition is used, matrix subtraction otherwise for the droid
        m_gameMatrix[i] += m_possibilities[index][i] * player;
        if (0 != m_gameMatrix[i] && m_gameMatrix[i] % 3 == 0) {
            // emit wining signal if any matrix value equals 3
            Q_EMIT won(m_gameMatrix[i] / 3);
            stopDroid();
            return;
        }
    }
    if (noMoreSelections()) {
        // emit tie signal if there are no more choices available
        // since there is only two players (1,-1) that means -2
        // represents a tie
        Q_EMIT won(-2);
        stopDroid();
        return;
    }
    if (send) {
        Q_EMIT sendSelection(index);
    }
}
Example #2
0
int TicTacToe::play(bool _xTurn, int pos) {
	bool win;
	
	if(!isRightTurn(_xTurn)) {
		return INVALID_TURN;
	}
	
	if(!isValidMove(pos)) {
		return INVALID_MOVE;
	}
	
	placeMove(_xTurn,pos);
	
	plotGame();
	
	win = won(_xTurn);
	xTurn = !xTurn;
	
	if(win) {
		resetGame();
		return WIN;
	}
	else if(isFull()){
		resetGame();
		return OVER;
	}
	else {
		return NO_WIN;
	}
}
Example #3
0
/**
  * clear(int row, int column, bool allowedClear)
  * clear recursively reveals all zeros and reveals its neighbors that are not mines
  * @param int - The row to inspect
  * @param int - The column to inspect
  * @param bool - If we are allowed to clear the particular cell. This is used when recursively clearing something not a zero -- it is a neighbor of a zero so it is not allowed to clear others
  */
void MainWindow::clear(int row, int column, bool allowedClear)
{
    //Retrieve the button
    QString coordinates = QString::number(row) + "," + QString::number(column);

    MineSweeperButton *buttonPushed = qobject_cast<MineSweeperButton *>(signalMapper->mapping(coordinates));

    //Ensure that the button is not flat, that the value is not a mine, that it is allowed to clear (not something that isn't a zero) and it isn't flagged
    if ( buttonPushed->isFlat () == false && game->getValue (row, column) != MINE && allowedClear == true && mineStatus[row][column] != FLAGGED_CELL)
    {
        buttonPushed->setFlat (true); //We're now flat

        //Set the image according to the value of the cell
        changeIcon(buttonPushed, row, column);

        cellsRevealed++;

        //If we have 90 cells revealed (10 mines, 90 not mines), we win the game!
        if (cellsRevealed == 90 && game->getValue(row, column) != MINE)
        {
            changeIcon(buttonPushed, row, column);
            won();
            return;
        }   // in case clearing occurs in the end of the game.

        //Make sure that we are allowed to clear
        if ( game->getValue (row, column) == 0)
            allowedClear = true;
        else
            allowedClear = false;

        //Recrusively call clear on all adjacent cells
        //Top left
        if ( (row-1) != -1 && (column -1) != -1)
            clear(row-1, column-1, allowedClear);
        //Top center
        if ( (row-1) != -1)
            clear(row-1, column, allowedClear);
        //Top right
        if ( (row-1) != -1 && (column + 1) != 10)
            clear(row-1, column+1, allowedClear);
        //Left
        if ( (column -1) != -1)
            clear(row, column-1, allowedClear);
        //Right
        if ( (column + 1) != 10)
            clear(row, column+1, allowedClear);
        //Bottom left
        if ( (row+1) != 10 && (column -1) != -1)
            clear(row+1, column-1, allowedClear);
        //Bottom center
        if ( (row+1) != 10)
            clear(row+1, column, allowedClear);
        //Bottom right
        if ( (row+1) != 10 && (column+1) != 10)
        {
            clear(row+1, column+1, allowedClear);
        }
    }
}
Example #4
0
   void score(int i,int l,int shots)
   {
	int n;
	for(n=0;n<3;n++)
	{sound(200);
	 cleardevice();
	 delay(250);
	 nosound();
	 settextstyle(4,0,8);
	 setcolor(6);
	 outtextxy(150,150,"Game Over");
	 setcolor(RED);
	 rect(i);
	 delay(350);}
	delay(100);
	getch();
	cleardevice();
	setbkcolor(RED);
	gotoxy(34,16);
	printf("Your Score:: %d",l*1000-::shots*150);
	gotoxy(33,17);
	printf("Highest Score:: 20000");
	delay(2500);
	getch();
	if(shots>=25)loose(i);
	else won(i);
   }
Example #5
0
// Runs the Game...
void Ultra1::App::Run( )
{
	// All of the game states we could be in...
	Intro intro( this );
	MainMenu menu( this );
	Game game( this );
	MapState map_state( this );
	WonState won( this );
	LostState lost( this );
	HelpState help( this );
	StoryState story( this );
	OptionsState options( this );

	// Must be entered into array in same order as the const values...
	GameState* states[] = { &intro, &menu, &game, &map_state, &won, &lost, &help, &story, &options };

	// We start in the intro...
	StateNumber current_state = INTRO_STATE;

	while( current_state != QUIT_STATE )
	{
		// Run the current state and assign the next state to it...
		current_state = states[current_state]->Run( );
	}
}
Example #6
0
int
main(int argc, char *argv[])
{
    // greet user with instructions
    greet();

    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < DIM_MIN || d > DIM_MAX)
    {
        printf("Board must be between %d x %d and %d x %d, inclusive.\n",
         DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);
        return 2;
    }

    // initialize the board
    init();

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw();

        // check for win
        if (won())
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
        int tile = GetInt();

        // move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // sleep thread for animation's sake
        usleep(500000);
    }

    // that's all folks
    return 0;
}
Example #7
0
	int HighestNumber::value(std::uint8_t player) const
	{
		if (won(player))
			return 1;
		else if (lost(player))
			return -1;
		else
			return 0;
	}
Example #8
0
int main(int argc, string argv[])
{
  // greets player
  greet();

  // ensures proper usage
  if (argc != 2) {
    printf("Usage: ./fifteen d\n");
    return 1;
  }

  // checks for valid dimensions
  d = atoi(argv[1]);
  if (d < MIN || d > MAX) {
    printf("Board must be between %i x %i and %i x %i, inclusive.\n",
	   MIN, MIN, MAX, MAX);
    return 2;
  }

  // initializes the board
  init();

  // accepts moves until game is won
  while (true) {
    // clears the screen
    clear();

    // draws the current state of the board
    draw();
    
    // saves the current state of the board (for testing)
    save();

    // checks for win
    if (won()) {
      printf("Congrats!\n");
      break;
    }

    // prompts for next move
    printf("Tile to move: ");
    int tile = GetInt();

    // moves if possible, else reports illegality
    if (!move(tile)) {
      printf("\nIllegal move.\n");
      usleep(500000);
    }

    // sleeps for animation's sake
    usleep(500000);
  }

  return 0;
}
Example #9
0
int main(int argc, string argv[])
{
    greet();
    
    if (argc != 2)
    {
        printf("Usage: ./fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < MIN || d > MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            MIN, MIN, MAX, MAX);
        return 2;
    }

    // initialize the board
    init();

    // accept moves until game is won
    while (true)
    {
        int tile;
        clear();
        draw();   
        save(); //for testing

        //if god mode on, go to god mode procedure
        if (godMode == 1)
            godSolve(d);
        
        // check for win
        if (won()) {
            printf("ftw!\n");
            break;
        }
            
        printf("Tile to move: ");
        tile = getIntOrGod();

        // move if possible, else report illegality
        if (!move(tile)){
            printf("\nIllegal move.\n");
            usleep(20000);
        }
        usleep(20000);
    }

    // that's all folks
    return 0;
}
Example #10
0
void Game::merge_to(int from_x, int from_y, int to_x, int to_y)
{
    assert_coords(from_x, from_y);
    assert_coords(to_x, to_y);
    assert(m_rects[from_x][from_y] != nullptr && m_rects[to_x][to_y] != nullptr);
    m_animator.add<Merge>(*m_rects[to_x][to_y]);
    int number = m_rects[to_x][to_y]->next_number();
    m_rects[from_x][from_y] = nullptr;

    if (!m_won && number == Definitions::GAME_WIN_NUMBER)
        won();
}
Example #11
0
//basically the loop from the main method, but taken out so it could
//be called separately by the godsolve procedure
void moveComplete (int tile) {
        
        move(tile);
        usleep(400);
        clear();
        draw();   
        save(); //for testing
        
        // check for win
        if (won()) {
            printf("ftw!\n");
            exit(0);
        }
}
Example #12
0
MainScene::MainScene(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainScene),
    m_time_counter(new QTimer(this)),
    m_who_am_i(NOT_PLAYER),
    m_click(new QSound(":/sounds/click.wav"))
{
    ui->setupUi(this);
    connect(ui->transferButton, SIGNAL(clicked(bool)),
            this, SLOT(toChangeTurn()));
    connect(ui->menuButton, SIGNAL(clicked(bool)),
            this, SIGNAL(shouldSetting()));
    connect(ui->undoButton, SIGNAL(clicked(bool)),
            this, SLOT(toSendUndo()));
    connect(ui->giveupButton, SIGNAL(clicked(bool)),
            this, SLOT(toSendGiveup()));
    connect(ui->transferButton, SIGNAL(clicked(bool)),
            m_click, SLOT(play()));
    connect(ui->menuButton, SIGNAL(clicked(bool)),
            m_click, SLOT(play()));
    connect(ui->undoButton, SIGNAL(clicked(bool)),
            m_click, SLOT(play()));
    connect(ui->giveupButton, SIGNAL(clicked(bool)),
            m_click, SLOT(play()));

    connect(this, SIGNAL(remainingTimeChanged(int)),
            this, SLOT(updateRemaining(int)));

    m_time_counter->setInterval(TIMER_INTERVAL);
    connect(m_time_counter, SIGNAL(timeout()),
            this, SLOT(reduceRemaining()));

    connect(ui->boardView, SIGNAL(won()),
            this, SIGNAL(gameWon()));
    connect(ui->boardView, SIGNAL(lost()),
            this, SIGNAL(gameLost()));
    connect(ui->boardView, SIGNAL(finished(bool)),
            this, SIGNAL(gameFinished(bool)));
    connect(ui->boardView, SIGNAL(placed(QPoint,bool,bool)),
            this, SIGNAL(shouldPlace(QPoint,bool,bool)));
}
int main(void){
    char *hand[LENGTH] = {"rock", "paper", "scissors"};
    int player_hand;
    int pc_hand;
    float wins = 0;
    float played_games = 0;
    srand(time(NULL));

    do{
        selection(&player_hand, &pc_hand);
        printf("Your hand is %d = %s. PC's hand is %s. %s!\n",
          player_hand, hand[player_hand], hand[pc_hand],
          draw(player_hand, pc_hand)? "It's a Draw" : won(&wins, &played_games, player_hand, pc_hand)? "You Win" : " You Lose");
    }while(continue_playing());

    printf("You won %.0f times\n", wins);
    printf("You played %.0f games\n", played_games);
    printf("Thanks for playing. You won %.1f%% of the games\n", (wins/played_games) * 100);

    return 0;
}
Example #14
0
void Game::process_play(const play_event& pl_event)
{
    for (const auto& oper : pl_event)
    {
        if (oper.first == play_event::operation::MOVE)
            move_to(oper.second.first.first, oper.second.first.second, oper.second.second.first, oper.second.second.second);
        else if (oper.first == play_event::operation::MERGE)
            merge_to(oper.second.first.first, oper.second.first.second, oper.second.second.first, oper.second.second.second);
    }


    auto random_block = pl_event.random_block();
    spawn_block(random_block.first, random_block.second.first, random_block.second.second);

    if (!m_won)
        if (m_won = pl_event.won())
            won();

    if (pl_event.lost())
        game_over();

    m_score += pl_event.score();
}
Example #15
0
int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < DIM_MIN || d > DIM_MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);
        return 2;
    }

    // open log
    FILE* file = fopen("log.txt", "w");
    if (file == NULL)
    {
        return 3;
    }

    // greet user with instructions
    greet();

    // initialize the board
    init();

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw();

        // log the current state of the board (for testing)
        for (int i = 0; i < d; i++)
        {
            for (int j = 0; j < d; j++)
            {
                fprintf(file, "%i", board[i][j]);
                if (j < d - 1)
                {
                    fprintf(file, "|");
                }
            }
            fprintf(file, "\n");
        }
        fflush(file);

        // check for win
        if (won())
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
        int tile = GetInt();
        
        // quit if user inputs 0 (for testing)
        if (tile == 0)
        {
            break;
        }

        // log move (for testing)
        fprintf(file, "%i\n", tile);
        fflush(file);

        // move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // sleep thread for animation's sake
        usleep(500000);
    }
    
    // close log
    fclose(file);

    // success
    return 0;
}
Example #16
0
int main(int argc, string argv[])
{
    // greet player
    greet();

    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < MIN || d > MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            MIN, MIN, MAX, MAX);
        return 2;
    }

    // initialize the board
    init(d, board);

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw(d, board);

        // saves the current state of the board (for testing)
        save();

        // check for win
        if (won(board, d))
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
        int tile = GetInt();

        // move if possible, else report illegality
        if (!move(tile, board, d))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }
        else if (move(tile, board, d))
        {
            complete(tile, board, d);
        }

        // sleep for animation's sake
        usleep(500000);
    }

    // that's all folks
    return 0;
}
Example #17
0
int
main(int argc, char *argv[])
{
    // define usage
    const char *usage = "Usage: sudoku n00b|l33t [#]\n";

    // ensure that number of arguments is as expected
    if (argc != 2 && argc != 3)
    {
        fprintf(stderr, usage);
        return 1;
    }

    // ensure that level is valid
    if (strcmp(argv[1], "debug") == 0)
        g.level = "debug";
    else if (strcmp(argv[1], "n00b") == 0)
        g.level = "n00b";
    else if (strcmp(argv[1], "l33t") == 0)
        g.level = "l33t";
    else
    {
        fprintf(stderr, usage);
        return 2;
    }

    // n00b and l33t levels have 1024 boards; debug level has 9
    int max = (strcmp(g.level, "debug") == 0) ? 9 : 1024;

    // ensure that #, if provided, is in [1, max]
    if (argc == 3)
    {
        // ensure n is integral
        char c;
        if (sscanf(argv[2], " %d %c", &g.number, &c) != 1)
        {
            fprintf(stderr, usage);
            return 3;
        }

        // ensure n is in [1, max]
        if (g.number < 1 || g.number > max)
        {
            fprintf(stderr, "That board # does not exist!\n");
            return 4;
        }

        // seed PRNG with # so that we get same sequence of boards
        srand(g.number);
    }
    else
    {
        // seed PRNG with current time so that we get any sequence of boards
        srand(time(NULL));

        // choose a random n in [1, max]
        g.number = rand() % max + 1;
    }

    // start up ncurses
    if (!startup())
    {
        fprintf(stderr, "Error starting up ncurses!\n");
        return 5;
    }

    // register handler for SIGWINCH (SIGnal WINdow CHanged)
    signal(SIGWINCH, (void (*)(int)) handle_signal);

    // start the first game
    if (!restart_game())
    {
        shutdown();
        fprintf(stderr, "Could not load board from disk!\n");
        return 6;
    }
    redraw_all();
    
    // initialize legal variable
    g.legal = true;
    
    // initialize won variable
    g.won = false;

    // let the user play!
    int ch;
    do
    {
        // refresh the screen
        refresh();

        // get user's input
        ch = getch();

        // capitalize input to simplify cases
        ch = toupper(ch);

        // process user's input
        switch (ch)
        {
            // start a new game
            case 'N': 
                g.number = rand() % max + 1;
                if (!restart_game())
                {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 6;
                }
                break;

            // restart current game
            case 'R': 
                if (!restart_game())
                {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 6;
                }
                break;

            // let user manually redraw screen with ctrl-L
            case CTRL('l'):
                redraw_all();
                break;
            
            // move cursor on the board   
            case KEY_DOWN:                
            case KEY_UP:
            case KEY_LEFT:
            case KEY_RIGHT:
                move_cursor(ch);
                break;
                
            case KEY_BACKSPACE:
            case KEY_DC:
            case 46: // .
            case 48: // 0
            case 49: // 1
            case 50: // 2
            case 51: // 3
            case 52: // 4
            case 53: // 5
            case 54: // 6
            case 55: // 7
            case 56: // 8
            case 57: // 9
                change_number(ch);
                if(!legal(ch))
                {
                    show_banner("Illegal Move...");
                    show_cursor();
                    g.legal = false;
                }
                else
                {
                    hide_banner();
                    show_cursor();
                    g.legal = true;
                }
                if(won(ch))
                {
                    show_banner("You Won The Game!!!");
                    g.won = true;
                }
                break;
        }
        

        // log input (and board's state) if any was received this iteration
        if (ch != ERR)
            log_move(ch);
    }
    while (ch != 'Q');

    // shut down ncurses
    shutdown();

    // tidy up the screen (using ANSI escape sequences)
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

    // that's all folks
    printf("\nkthxbai!\n\n");
    return 0;
}
Example #18
0
int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < DIM_MIN || d > DIM_MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);
        return 2;
    }

    // open log
    FILE* file = fopen("log.txt", "w");
    if (file == NULL)
    {
        return 3;
    }

    // GOD_MODE activated?
    bool gm = false;

    // greet user with instructions
    greet();

    // initialize the board
    init();

    // randomize board
    random_board();

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw();

        // log the current state of the board (for testing)
        for (int i = 0; i < d; i++)
        {
            for (int j = 0; j < d; j++)
            {
                fprintf(file, "%i", board[i][j]);
                if (j < d - 1)
                {
                    fprintf(file, "|");
                }
            }
            fprintf(file, "\n");
        }
        fflush(file);

        // check for win
        if (won())
        {
            if (gm)
                printf("That's easy! (;\n");
            else
                printf("ftw!\n");
            break;
        }

        // Get user input 
        int tile;
        do {
            // prompt for move
            printf("Tile to move: ");
            char* input = GetString();
        
            // start the GOD mode
            if (strcmp(input, GOD_MODE) == 0)
            {
                tile = 0;
                if (d > 4)
                {
                    printf("\nThat is too big for me!\n");
                    usleep(500000);
                    break;
                }
                gm = true;
                solve();
                free(input);
                break;
            }
            else if (strcmp(input, NEW_GAME) == 0)
            {
                random_board();
                free(input);
                break;
            }
            else
            {
                tile = atoi(input);
            }
            
            if (tile > 0 && tile < d*d)
            {
                free(input);
                break;
            }
        } while (1);


        // log move (for testing)
        fprintf(file, "%i\n", tile);
        fflush(file);

        // move if possible, else report illegality
        if (tile > 0)
        {
            if (!move(tile))
            {
                printf("\nIllegal move.\n");
                usleep(500000);
            }
        }

        // sleep thread for animation's sake
        usleep(500000);
    }

    // close log
    fclose(file);

    // success
    return 0;
}
Example #19
0
int main(int argc, string argv[])
{
    // greet player
    greet();

    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < MIN || d > MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            MIN, MIN, MAX, MAX);
        return 2;
    }
    // initialize the board
    init();
	
	// initializing code to work with god mode
	/*int god = 0;
	int goal[d][d];
	int count = 1;
	for(int i = 0; i < d; i++)
	{
		for(int j = 0; j < d; j++)
		{
			if(count == d * d)
			{
				count = 0;
			}
			goal[i][j] = count;
			count++;
		}
	}*/

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw();

        // saves the current state of the board (for testing)
        save();

        // check for win
        if (won())
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
		int tile;
		
		tile = GetInt();
		
		// broken god mode
		/*int last;
		int flag = 0;
		while(flag == 0)
		{
			if(god == 0)
			{
				char* input = GetString();
				if(strcmp(input, "GOD") == 0)
				{
					god = 1;
					tile = 0;
					flag++;
				}
				else if(atoi(input) > 0)
				{
					tile = atoi(input);
					flag++;
				}
				else
				{
					printf("Retry: ");
				}
			}
			else
			{
				int tmp[d][d];
				int sits[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
				int priority[4];
				int changed[4];
				for(int i = 0; i < 4; i++)
				{
					priority[i] = 0;
					changed[i] = 0;
					if(blank[0] + sits[i][0] > -1 && blank[0] + sits[i][0] < d && blank[1] + sits[i][1] > -1 && blank[1] + sits[i][1] < d)
					{
						for(int j = 0; j < d; j++)
						{
							for(int k = 0; k < d; k++)
							{
								tmp[j][k] = board[j][k];
							}
						}
						changed[i] = tmp[blank[0] + sits[i][0]][blank[1] + sits[i][1]];
						if(changed[i] == last)
						{
							priority[i] = priority[i] + 3;
						}
						int temp = tmp[blank[0]][blank[1]];
						tmp[blank[0]][blank[1]] = tmp[blank[0] + sits[i][0]][blank[1] + sits[i][1]];
						tmp[blank[0] + sits[i][0]][blank[1] + sits[i][1]] = temp;
						for(int j = 0; j < d; j++)
						{
							for(int k = 0; k < d; k++)
							{
								for(int l = 0; l < d; l++)
								{
									for(int m = 0; m < d; m++)
									{
										if(goal[j][k] == tmp[l][m] && goal[j][k] > 0)
										{
											priority[i] = abs(j - l) + abs(k - m) + priority[i];
										}
									}
								}
							}
						}
					}
				}
				int sorted = 0;
				do
				{
					sorted = 0;
					for(int i = 0; i < 4 - 1; i++)
					{
						if(priority[i] > priority[i + 1])
						{
							int temp = priority[i];
							priority[i] = priority[i + 1];
							priority[i + 1] = temp;
							int temp1 = changed[i];
							changed[i] = changed[i + 1];
							changed[i + 1] = temp1;
							sorted++;
						}
					}
				}
				while(sorted != 0);
				for(int i = 0; i < 4; i++)
				{
					if(priority[i] != 0)
					{
						tile = changed[i];
						last = changed[i];
						break;
					}
				}
				flag++;
			}
		}*/
        
        // move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // sleep for animation's sake
        usleep(250000);
    }

    // that's all folks
    return 0;
}
Example #20
0
/**
  * revealCell()
  * Reveals the cell at the given coordinate, also handles losing / winning
  */
void MainWindow::revealCell(QString coordinates)
{
    //Obtain the coordinates
    QStringList results = coordinates.split(",");

    if ( results.size() != 2) //Ensure that we receive two coordinates
        qFatal("Less than two numbers received");

    int row = results.at(0).toInt();
    int column = results.at(1).toInt();

    //If we already finished the game.. we won't do anything here
    if (hasFinished)
    {
        return;
    }
    else
    {
        cellsRevealed++;
    }

    //If it is flagged, we will ignore the mine
    if ( mineStatus[row][column] == FLAGGED_CELL || mineStatus[row][column] == QUESTION_CELL )
    {
            cellsRevealed--;
            return;
    }

    //Get the button we just pushed
    MineSweeperButton *buttonPushed = qobject_cast<MineSweeperButton *>(signalMapper->mapping(coordinates));


    //If it is flat.. we already pushed it so ignore it
    if (buttonPushed->isFlat())
    {
            cellsRevealed--;
            return;
    }

    //If we have 90 cells revealed (10 mines, 90 not mines), we win the game!
    if (cellsRevealed == 90 && game->getValue(row, column) != MINE)
    {
        changeIcon(buttonPushed, row, column);
        won();
        return;
    }

    //Recrusively clear the squares if we reveal a zero
    if ( game->getValue (row, column) == 0 ) {
        cellsRevealed--;
        clear(row, column, true);
    }

    //Set the image according to the value of the cell
    changeIcon(buttonPushed, row, column);

    buttonPushed->setFlat(true);    // if revealed, set button flat

    //If we reveal a mine, we just lost :(
    if ( game->isMine( row, column ) )
    {
        lost();
        cellsRevealed--;
        return;
    } else {
        //Phew, it's not a mine! We're happy!!!!!!! :D
        ui->smileyFace->setIcon(QIcon(":/images/normal_face.png"));
    }

    //If we haven't started yet, let's start the counter
    if ( !hasStarted )
    {
        timer->start(1000);
        hasStarted = true;
    }
}
Example #21
0
/*
 * Main driver for the game.
 */
int
main(int argc, char **argv) {
    // define usage
    const char *usage = "Usage: sudoku n00b|l33t [#]\n";

    // ensure that number of arguments is as expected
    if (argc != 2 && argc != 3) {
        fprintf(stderr, usage);
        return 1;
    }

    // ensure that level is valid
    if (!strcmp(argv[1], "debug"))
        g.level = "debug";
    else if (!strcmp(argv[1], "n00b"))
        g.level = "n00b";
    else if (!strcmp(argv[1], "l33t"))
        g.level = "l33t";
    else {
        fprintf(stderr, usage);
        return 2;
    }

    // n00b and l33t levels have 1024 boards; debug level has 9
    int max = (!strcmp(g.level, "debug")) ? 9 : 1024;

    // ensure that #, if provided, is in [1, max]
    if (argc == 3) {
        // ensure n is integral
        char c;
        if (!sscanf(argv[2], " %d %c", &g.number, &c) == 1) {
            fprintf(stderr, usage);
            return 3;
        }

        // ensure n is in [1, max]
        if (g.number < 1 || g.number > max) {
            fprintf(stderr, "That board # does not exist!\n");
            return 4;
        }

        // seed PRNG with # so that we get same sequence of boards
        srand(g.number);
    }
    else {
        // seed PRNG with current time so that we get any sequence of boards
        srand(time(NULL));

        // choose a random n in [1, max]
        g.number = rand() % max + 1;
    }

    // start up ncurses
    if (!startup()) {
        fprintf(stderr, "Error starting up ncurses!\n");
        return 6;
    }

    // register handler for SIGWINCH (SIGnal WINdow CHanged)
    signal(SIGWINCH, (void (*)(int)) handle_signal);

    // start the first game
    if (!restart_game()) {
        shutdown();
        fprintf(stderr, "Could not load board from disk!\n");
        return 7;
    }
    redraw_all();

    // let the user play!
    int ch;
    do {
        // refresh the screen
        refresh();

        // get user's input
        ch = getch();

        // capitalize input to simplify cases
        ch = toupper(ch);

        // process user's input
        switch (ch) {

            // left arrow key
            case KEY_LEFT:
            case 'H':
                if (--g.x < 0)
                    g.x += DIM;
                hide_banner();
                show_cursor();
                break;
            // right arrow key
            case KEY_RIGHT:
            case 'L': 
                if (++g.x >= DIM)
                    g.x -= DIM;
                hide_banner();
                show_cursor();
                break;
            // up arrow key
            case KEY_UP:
            case 'K':
                if (--g.y < 0)
                    g.y += DIM;
                hide_banner();
                show_cursor();
                break;
            // down arrow key
            case KEY_DOWN:
            case 'J':
                if (++g.y >= DIM)
                    g.y -= DIM;
                hide_banner();
                show_cursor();
                break;

            // enable user to enter numbers
            case '1': case '2': 
            case '3': case '4': 
            case '5': case '6': 
            case '7': case '8': 
            case '9':
                if (g.given[g.y][g.x] == false && validate(ch) == true) {
                    enter_number(ch);
                    draw_numbers();
                    show_cursor();
                    won();
                }
                break; 

            // delete a number
            case KEY_BACKSPACE:
            case KEY_DC:
            case '.':
            case '0':
                if (g.given[g.y][g.x] == false) {
                    g.board[g.y][g.x] = 0; 
                    draw_numbers();
                    hide_banner();
                    show_cursor();
                }
                break;
            // start a new game
            case 'N': 
                g.number = rand() % max + 1;
                if (!restart_game()) {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 7;
                }
                break;

            // restart current game
            case 'R': 
                if (!restart_game()) {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 7;
                }
                break;

            // let user manually redraw screen with ctrl-L
            case CTRL('l'):
                redraw_all();
                break;
        }   // end switch statement

        // log input (and board's state) if any was received this iteration
        if (ch != ERR)
            log_move(ch);

    } while (ch != 'Q');

    // shut down ncurses
    shutdown();

    // tidy up the screen (using ANSI escape sequences)
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

    // kthxbai
    printf("\nkthxbai!\n\n");
    return 0;
}
Example #22
0
bool play(bool with_ai)
{
	char grid[SIZE][SIZE];
	Index2d pos;

	int moves = 0;
	int max_moves = SIZE * SIZE;

	static int player1_score = 0, player2_score = 0;

	srand((unsigned)time(NULL));
	rand();

	/* Initialize grid */
	memset(grid, ' ', SIZE * SIZE);

	char player1 = rand() % 2 ? 'x' : 'o';
	char player2 = (player1 == 'x' ? 'o' : 'x');

	if (with_ai) {
		printf("You are %c\n", player1);
		if (player1 == 'x')
			print_grid(grid);
	}
	else {
		printf("Player 1 is %c. Player 2 is %c\n", player1, player2);
		print_grid(grid);
	}

	if (player1 == 'o') {
		if (with_ai)
			ai_turn(grid, player1, player2);
		else {
			puts("Player 2's turn");
			player_turn(grid, player2);
		}
		++moves;
		print_grid(grid);
	}

	for (;;) {
		/* Player 1 */
		if (moves < max_moves) {
			if (!with_ai)
				puts("Player 1's turn");
			pos = player_turn(grid, player1);
			++moves;

			if (won(grid, pos, player1)) {
				if (with_ai)
					puts("You won");
				else
					puts("Player 1 won");
				++player1_score;
				break;
			}

			/* Don't print the grid before the AI's turn */
			if (!with_ai)
				print_grid(grid);
		}

		/* Player 2 / AI */
		if (moves < max_moves) {
			if (with_ai)
				pos = ai_turn(grid, player1, player2);
			else {
				puts("Player 2's turn");
				pos = player_turn(grid, player2);
			}
			++moves;

			if (won(grid, pos, player2)) {
				if (with_ai)
					puts("You lost");
				else
					puts("Player 2 won");
				++player2_score;
				break;
			}

			print_grid(grid);
		}

		if (moves == max_moves) {
			puts("Tie");
			break;
		}
	}

	print_grid(grid);
	printf("Player 1  Player 2\n"
		"--------  --------\n"
		"%8d%10d\n", player1_score, player2_score);

	return prompt_bool("Play again?", true);
}
Example #23
0
void Player::win()
{
    addWin();
    emit won();
}
Example #24
0
// the main function
void _main(void) {
    unsigned int difficulty = NORMAL;
    short int key=0;
    short int keys[8];
    unsigned int level_num = 1;
    unsigned short int score = 0;
    int done = 0;
    unsigned int money = 0;
    int cannon_level = 1;
    int missile_level = 0;
    char map[12][MAP_SIZE];

    // seed the random numbers
    randomize();
    // get the key masks
    getKeyMasks(keys);


    INT_HANDLER interrupt1 = GetIntVec(AUTO_INT_1);  // this will save auto int 1

    // draw title screen and wait for keypress
    GrayOn();
    drawTitle(2);
    ngetchx();

    //draw background title screen and menu
    drawTitle(1);
    drawWords(difficulty);
    POSITION pointer = {10,0};
    drawPointer(pointer);
    // the menu loop
    while (1) {
        key = ngetchx();
        if (key == KEY_ENTER && pointer.y != OPTIONS) {
            if (pointer.y == PLAY) break;
            if (pointer.y == HIGH_SCORES) printHiScores();
            if (pointer.y == HELP) doHelp();
            if (pointer.y == ABOUT) {
                SetIntVec(AUTO_INT_1,interrupt1);
                GrayOff();
                exit(0);
            }
            GraySetAMSPlane(LIGHT_PLANE);
            clrscr();
            GraySetAMSPlane(DARK_PLANE);
            clrscr();
            drawTitle(1);
            drawWords(difficulty);
            pointer=(POSITION) {
                10,0
            };
            drawPointer(pointer);
        }
        if (key == KEY_LEFT && pointer.y == OPTIONS && difficulty < VERY_EASY) {
            difficulty+=1;
            GraySetAMSPlane(LIGHT_PLANE);
            clrscr();
            GraySetAMSPlane(DARK_PLANE);
            clrscr();
            drawTitle(1);
            drawPointer(pointer);
            drawWords(difficulty);
        }
        if (key == KEY_RIGHT && pointer.y == OPTIONS && difficulty > IMPOSSIBLE)  {
            difficulty-=1;
            GraySetAMSPlane(LIGHT_PLANE);
            clrscr();
            GraySetAMSPlane(DARK_PLANE);
            clrscr();
            drawTitle(1);
            drawPointer(pointer);
            drawWords(difficulty);
        }
        if (key == KEY_UP || key == KEY_DOWN) drawPointer(pointer);
        if (key == KEY_UP && pointer.y > 0) pointer.y--;
        if (key == KEY_DOWN && pointer.y < 4) pointer.y++;
        if (key == KEY_UP || key == KEY_DOWN) drawPointer(pointer);
    }
    key = 0;
    // turn off gray, so we can destroy auto-int-1 and not mess it up
    GrayOff();

    // DESTROY auto-interrupt 1 so as not to mess up _rowread
    SetIntVec(AUTO_INT_1,DUMMY_HANDLER);

    // turn gray back on
    GrayOn();

    // randomize the map
    randomMap(difficulty, map, level_num);
    //the main game loop
    while (!quit() && !done) {
        done = 0;
        int fin = 0;
        int win = 0;
        int forward = 0;
        int map_x_location = 0;
        int laser = 0;
        int justLaser = 0;
        int missile = 0;
        int justMissile = 0;
        int missileSlow = 2;
        POSITION laserPos;
        POSITION oldLaserPos;
        POSITION missilePos;
        POSITION oldMissilePos;
        POSITION oldShip;
        POSITION ShipPos = {0,5};

        // we need to disable gray temporarily to do the shop screen...
        GrayOff();
        SetIntVec(AUTO_INT_1, interrupt1);
        shop(&money, &cannon_level, &missile_level);
        SetIntVec(AUTO_INT_1, DUMMY_HANDLER);
        GrayOn();

        // draws the level
        Draw_Map(map_x_location, map, ShipPos, laserPos, laser, missilePos, missile);


        // the loop for the action in the level
        while (!quit()) {

            // if the user has a missile out, deal with it
            if (missile && missileSlow == 2) {
                missileSlow = 1;
                oldMissilePos = missilePos;
                missilePos.x++;
                missilePos.y+=missile;
                if (missilePos.x > map_x_location + 20) missile = 0;
                if (missilePos.y < 0 || missilePos.y > 12) {
                    missile = 0;
                    eraseMissile(missilePos, map_x_location);
                }
                if (blowWall(missilePos,map)) {
                    if (map[missilePos.y][missilePos.x] < 4) {
                        map[missilePos.y][missilePos.x]-=3;
                        if (map[missilePos.y][missilePos.x] == 0) {
                            score++;
                            money+=BLOCK_VALUE;
                        }
                    }
                    if (map[missilePos.y][missilePos.x] < 0) map[missilePos.y][missilePos.x] = 0;
                    missile = 0;
                    justMissile = 0;
                    Draw_Map(map_x_location,map,ShipPos,laserPos,laser,missilePos,missile);
                }
                // if the shot was just fired, then there wont be one to erase
                if (!justMissile && missile == 1) {
                    moveMissile(oldMissilePos,missilePos,map_x_location);
                } else if (missile == 1) {
                    drawMissile(missilePos,map_x_location);
                    justMissile = 0;
                } else if (!justMissile && missile == -1) {
                    moveUpMissile(oldMissilePos, missilePos, map_x_location);
                } else if (missile == -1) {
                    drawUpMissile(missilePos, map_x_location);
                    justMissile = 0;
                }

            } else {
                missileSlow++;
            }

            // if the user has a laser shot that is still going, continue it
            if (laser) {
                oldLaserPos = laserPos;
                laserPos.x++;
                if (laserPos.x > map_x_location + 20) laser=0;
                if (blowWall(laserPos,map)) {
                    if (map[laserPos.y][laserPos.x] < 4) {
                        map[laserPos.y][laserPos.x]-=cannon_level;
                        if (map[laserPos.y][laserPos.x] <= 0) {
                            score++;
                            money+=BLOCK_VALUE;
                            map[laserPos.y][laserPos.x] = 0;
                        }
                    } else if (map[laserPos.y][laserPos.x] == 4 && cannon_level == 4) {
                        map[laserPos.y][laserPos.x] = 1;
                    }
                    laser = 0;
                    justLaser = 0;
                    Draw_Map(map_x_location,map,ShipPos,laserPos,laser, missilePos, missile);
                }
                // if the shot was just fired, then there wont be one to erase
                if (!justLaser && laser) {
                    moveLaser(oldLaserPos,laserPos,map_x_location);
                } else if (laser) {
                    drawLaser(laserPos,map_x_location);
                    justLaser = 0;
                }
            }

            // scroll the screen forward one block every (difficulty) time through the main loop
            if (forward == difficulty) {
                map_x_location++;
                ShipPos.x++;
                forward = 0;
                if (map_x_location >= MAP_SIZE - 20) {
                    win = 1;
                    level_num++;
                    break;
                }
                // if you ran into a wall, quit
                if (detectWall(ShipPos,map)) {
                    win = 1;
                    score /= 2 ;
                    break;
                }
                Draw_Map(map_x_location,map,ShipPos,laserPos,laser, missilePos, missile);
            } else {
                forward++;
            }

            // if you ran into a wall, quit
            if (detectWall(ShipPos,map)) {
                win = 1;
                score = 0;
                break;
            }

            if (_rowread(~((short)(1<<1))) & (1<<6) && _rowread(~((short)(1<<2))) & (1<<6)) {
                win = 1;
                level_num++;
                break;
            }

            // get keypresses
            key = _rowread(ARROW_ROW);

            // if the user pressed right, move the ship right
            if (key & keys[RIGHT]) {
                oldShip = ShipPos;
                ShipPos.x++;
                if (ShipPos.x > map_x_location + 18) ShipPos.x--;
                if (!detectWall(ShipPos,map)) {
                    moveShip(oldShip,ShipPos,map_x_location);
                }	else {
                    win = 1;
                    score = 0;
                    break;
                }
            }
            // If the user pressed left, move the ship left
            if (key & keys[LEFT]) {
                oldShip = ShipPos;
                ShipPos.x--;
                if (ShipPos.x < map_x_location) ShipPos.x++;
                if (!detectWall(ShipPos,map)) {
                    moveShip(oldShip,ShipPos,map_x_location);
                } else {
                    win = 1;
                    score = 0;
                    break;
                }
            }

            // if the user pressed up, move the ship up
            if (key & keys[UP]) {
                oldShip = ShipPos;
                if (ShipPos.y - 1 < 0) {
                    ShipPos.y = 0;
                } else {
                    ShipPos.y--;
                }
                if (!detectWall(ShipPos,map))	{
                    moveShip(oldShip,ShipPos,map_x_location);
                } else {
                    win = 1;
                    score = 0;
                    break;
                }
            }

            // if the user pressed down, move the ship down
            if (key & keys[DOWN]) {
                oldShip = ShipPos;
                ShipPos.y++;
                if (ShipPos.y > 10) ShipPos.y = 10;
                if (!detectWall(ShipPos,map)) {
                    moveShip(oldShip,ShipPos,map_x_location);
                } else {
                    win = 1;
                    score = 0;
                    break;
                }
            }

            // if 2nd was pushed, fire the laser
            if (key & keys[SECOND]) {
                if (!laser) {
                    justLaser = 1;
                    laser = 1;
                    laserPos.x = ShipPos.x + 1;
                    laserPos.y = ShipPos.y;
                }
            }

            // if diamond was pushed fire the downward missiles
            if (key & keys[DIAMOND]) {
                if (missile_level == 3 || missile_level == 1) {
                    if (!missile) {
                        justMissile = 1;
                        missile = 1;
                        missileSlow = 2;
                        missilePos.x = ShipPos.x;
                        missilePos.y = ShipPos.y;
                    }
                }
            }

            // if shift was pushed fire the upward missiles
            if (key & keys[SHIFT]) {
                if (missile_level == 2 || missile_level == 3) {
                    if (!missile) {
                        justMissile = 1;
                        missile = -1;
                        missileSlow = 2;
                        missilePos.x = ShipPos.x;
                        missilePos.y = ShipPos.y;
                    }
                }
            }

            /*if (key & keys[ALPHA]) {
            score += 10;
            }*/
            // slow down the program because _rowread is too fast
            delay();
        }



        // back to the overall game loop
        if (win) {
            if (level_num <= LEVEL_NUM) {
                won(difficulty, map, level_num);
            } else {
                fin = 1;
                break;
            }
        }
    }

    // the user left, either by winning or quitting, so make sure everything is reset so the calc will be fine
    GrayOff();
    SetIntVec(AUTO_INT_1,interrupt1);
    hiScoresGo(score, difficulty, level_num);
}
int main()
{
	int player, opponent;
	
	player = 2;
	opponent = 1;
	
	int cellsFilled = 0;
	int o_move, p_move;
	
	display();
	
	while(cellsFilled < 9){
		
		if( won(player) ){
			printf("Sorry! You lose...\n\n");
			return 0;
		}else if( won(opponent) ){
			printf("You Win!!\n\n");
			return 0;
		}
		
		
		if( (p_move = definitiveOffenseDefense(player)) >= 0 ){
			board[p_move/3][p_move%3] = player;
			
		}else if( (p_move = definitiveOffenseDefense(opponent)) >= 0 ){
			board[p_move/3][p_move%3] = player;
		}else if( cellsFilled == 3 && (p_move = diagonalCorrection(player, opponent)) >= 0 ){
			board[p_move/3][p_move%3] = player;
		
		}else if( (p_move = tentativeOffenseDefense(player)) >= 0 ){
			board[p_move/3][p_move%3] = player;
		
		}else if( (p_move = tentativeOffenseDefense(opponent)) >= 0 ){
			board[p_move/3][p_move%3] = player;
		
		}else if( (p_move = motion(player)) >= 0 ){
			board[p_move/3][p_move%3] = player;
		
		}else{
			p_move = prioritizedSelection();
			board[p_move/3][p_move%3] = player;
		}		
		
		cellsFilled++;

		display();
		printf("%d\n", cellsFilled);		
		
		if(cellsFilled >= 9)
			break;
		
		vector<int> coord = prompt();
		o_move = coord[0]*3 + coord[1];	
				
		board[o_move/3][o_move%3] = opponent;
		
		cellsFilled++;
		
		
	}
	
	display();
	
	printf("It's a Draw!\n");		
	return 0;
}