KrecikApp::Result KrecikApp::run() { init(); all.restart(); lastTouch.restart(); running = true; while(running) { win.clear(); events(); update(); if(isWin() || isLose()) running = false; display(); } running = false; Result r; r.pts = pts; r.distance = getCarPos().x; r.time = all.getElapsedTime(); r.win = isWin(); return r; }
bool GameScene::isGameOver() { if (isWin()) { return false; } if (mIsGameOver) { return true; } // do the check mIsGameOver = true; for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { if (mCards[x][y]->getNumber() == 0 || (x < 3 && mCards[x][y]->getNumber() == mCards[x + 1][y]->getNumber()) || (x > 0 && mCards[x][y]->getNumber() == mCards[x - 1][y]->getNumber()) || (y < 3 && mCards[x][y]->getNumber() == mCards[x][y + 1]->getNumber()) || (y > 0 && mCards[x][y]->getNumber() == mCards[x][y - 1]->getNumber())) { mIsGameOver = false; break; } } } return mIsGameOver; }
/******************************************************************************\ * main * \******************************************************************************/ int main(void) { int col; char p; struct timeval tv; gettimeofday(&tv, NULL); srandom(getpid() ^ ~getuid() ^ tv.tv_sec ^ tv.tv_usec); readboard(); do col = random() % columns; while (board[col * rows + rows - 1] != 's'); if (random() % 8) p = 'b'; else p = 'g'; printBoard(board); isWin(board); freeboard(); printf("(%d,%c)", col+1, p); return 0; } /* main */
void MiniMax::minimize(tree& state, int depth, int alpha, int beta) { /* Their turn: * Find the worst (for us, best for opponent) move from here and take its * score for the current state */ scoreState(state); if (isWin(state.score)) { return; } if (boardFull(state)) { state.score = 0; return; } if (depth <= 0) { // Base case. Run the heuristic. return; } // Recursive case. Take the min of the maxes. int v = std::numeric_limits<int>::max(); size_t numChildren = state.children.size(); for (size_t i = 0; i < numChildren; ++i) { try { state.children[i] = makeMove(state, i, false); } catch (const std::runtime_error&) { continue; } state.children[i].move = i; maximize(state.children[i], --depth, alpha, beta); //favor moves in the middle if (i == state.children.size() / 2 && !isWin(state.children[i].score)) { --state.children[i].score; } v = std::min(v, state.children[i].score); if (v <= alpha) { // ***PRUNE*** state.score = v; return; } beta = std::min(beta, v); } // We didn't prune. state.score = v; }
void GameScene::doCheck() { bool isGameOver = true; //结束边界 4*4的card数值>0 且 相邻card没有相同数值 //4*4的card数值>0 不能在创建Number //判断每一个的上下左右和自己是否相同 for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { if (cardArr[x][y]->getNumber() == 0 || (x<3 && cardArr[x][y]->getNumber() == cardArr[x+1][y]->getNumber()) || (x>0 && cardArr[x][y]->getNumber() == cardArr[x-1][y]->getNumber()) || (y<3 && cardArr[x][y]->getNumber() == cardArr[x][y+1]->getNumber()) || (y>0 && cardArr[x][y]->getNumber() == cardArr[x][y-1]->getNumber()) ) { isGameOver = false; } } } if (isWin()) { successLayer = LayerColor::create(Color4B(0, 0, 0, 180)); Size winSize = Director::getInstance()->getWinSize(); Point centerPos = Point(winSize.width / 2, winSize.height / 2); auto gameOverTitle = Label::createWithSystemFont("YOU WIN","Consolas",80); gameOverTitle->setPosition(centerPos); successLayer->addChild(gameOverTitle); getParent()->addChild(successLayer,1); scheduleOnce(SEL_SCHEDULE(&GameScene::removeSuccessLayer), 2); return; } //isGameOver = true; if (isGameOver) { log("game over"); UserDefault::getInstance()->setBoolForKey("history", false); HighScore::getInstance()->setScore(score); GameOverLayer *gameoverLayer = GameOverLayer::create(Color4B(0, 0, 0, 180)); getParent()->addChild(gameoverLayer,1); Director::getInstance()->pause(); } else { if (shouldCreateCardNumber()) { createCardNumber(); saveStatus(); } } }
int main() { #ifdef debug printf("%X %X\n",&player,main); #endif do { printf("请选择走棋次序。\n输入1先走,或者-1后走。"); scanf("%d",&player); } while(player!=1&&player!=-1); int pl; //落子位置 DrawField(); int i; for(i=1;i<=9;i++) { if(isWin())break; if(player==1) { printf("请输入落子位置:"); scanf("%d",&pl); if(pl>9||pl<1||field[pl]!=0) { printf("输入错误,无此格子或格内已有子\n请重新输入:"); i--; DrawField(); continue; } else { field[pl]=player; player=-player; if(isWin())break; } } else AI(); } if(i>=9)printf("平局\n"); else printf("赢家是%d\n",sym(-player)); getchar();getchar(); //延迟窗口关闭 return 0; }
void PorkSendPage::on_PromptButton_clicked() { if(!isStart) return; for(int i = 1; i < map_row - 1; i++) { for(int j = 1; j < map_col - 1; j++) { for(int x = 1; x < map_row - 1; x++) { for(int y = 1; y < map_col - 1; y++) { if(i == j&&x == y) { continue; } if(arr_map[i][x] == EMPTY) { continue; } if(arr_map[j][y] == EMPTY) { continue; } if(arr_map[i][x] != arr_map[j][y]) { continue; } if(isWin(i,j,x,y)) { rects.clear(); rects.push_back(QPoint(PHWIDTH * x,PHHEIGHT *i)); rects.push_back(QPoint(PHWIDTH * y,PHHEIGHT * j)); update(); QEventLoop loop; QTimer::singleShot(300, &loop, SLOT(quit())); loop.exec(); rects.clear(); lines.clear(); update(); return true; } } } } } }
void MyGame::move(int i,int j,bool click){ if(!click){ if(actUserField[i][j]==0)actUserField[i][j]=1; if(field[i][j]==-1&&actUserField[i][j]!=2){ emit gameOver(false); boom(); } else if(field[i][j]==0&&actUserField[i][j]!=2){ expand(i,j); if(isWin()){ emit gameOver(true); boom(); } } else{ if(isWin()&&actUserField[i][j]!=2){ emit gameOver(true); boom(); } } } else{ if(actUserField[i][j]!=1&&actUserField[i][j]!=2){ actUserField[i][j]=2; counting--; emit changeBomb(counting); } else if(actUserField[i][j]==2){ actUserField[i][j]=0; counting++; emit changeBomb(counting); } } }
void AI() { for(int j=1;j<=9;j++) { if(field[j]==0) { field[j]=player; if(isWin())goto finish; field[j]=0; } } for(int j=1;j<=9;j++) { if(field[j]==0) { field[j]=-player; if(isWin()){field[j]=player;goto finish;} field[j]=0; } } if(field[5]==0){field[5]=player;goto finish;} // the next can be inprove if((field[1]!=0||field[9]!=0)&&field[3]==0){field[3]=player;goto finish;} if(field[3]!=0&&field[9]==0){field[9]=player;goto finish;} if(field[7]!=0&&field[1]==0){field[1]=player;goto finish;} if(field[2]!=0&&field[4]==0){field[4]=player;goto finish;} if(field[4]!=0&&field[2]==0){field[2]=player;goto finish;} if(field[8]!=0&&field[4]==0){field[4]=player;goto finish;} if(field[6]!=0&&field[8]==0){field[8]=player;goto finish;} for(int q=1;q<=9;q++) { if(field[q]==0) { field[q]=player;break; } } finish:player=-player;DrawField(); }
//采用博弈树来分析 //调用c语言 void AiGame::ComMoveChess() { if(!win){ QPoint whiteGo;//电脑的颜色 int x,y; int level = 2; x = 0; y = 0; int flag = 1; if(clickcount == 1){ //电脑第一次落子 while(flag){ int flag_randomPick = qrand()%7; FindFirstChess(&x,&y,chess,flag_randomPick); if(Position(x,y,chess) == 0) //直到落子合法才使flag=0退出循环 flag = 0; } } else{ switch(level){ //因为level是采用下拉框,所以不用做异值判断 case 1:{ robot_level1(level,&x,&y,chess);//只会防守 break; } case 2:{ robot_level2(level,&x,&y,chess);//会适当进攻 break; } case 3:{ //todo //采用棋谱 break; } } } clickcount++; movechess(x,y); win = isWin(x,y); if(win) { QMessageBox::information(this, "RobotWin", "RobotWin", QMessageBox::Ok); qDebug()<<"win"; } } else { QMessageBox::information(this, "YouWin", "YouWin", QMessageBox::Ok); qDebug()<<"win"; } }
bool validTicTacToe(vector<string>& board) { const auto FIRST = 'X', SECOND = 'O'; const auto x_count = accumulate(board.cbegin(), board.cend(), 0, [&FIRST](int accu, const string& s) { return accu + count(s.cbegin(), s.cend(), FIRST); }); const auto o_count = accumulate(board.cbegin(), board.cend(), 0, [&SECOND](int accu, const string& s) { return accu + count(s.cbegin(), s.cend(), SECOND); }); if (o_count != x_count - 1 && o_count != x_count) { return false; } if (isWin(board, FIRST) && o_count != x_count - 1) { return false; } if (isWin(board, SECOND) && o_count != x_count) { return false; } return true; }
bool GameScene::checkWin() { if (isWin()) { updateBestScore(); const Point& visibleOrigin = Director::getInstance()->getVisibleOrigin(); const Size& visibleSize = Director::getInstance()->getVisibleSize(); const Point& center = Point(visibleOrigin.x + visibleSize.width / 2.0f, visibleOrigin.y + visibleSize.height / 2.0f); auto sucessLayer = LayerColor::create(Color4B(0, 0, 0, 220)); auto winGameLabel = Label::createWithSystemFont("YOU WIN", "Consolas", 100); winGameLabel->setPosition(Point(center.x, center.y + 180)); sucessLayer->addChild(winGameLabel); char score[64]; sprintf(score, "SCORE %d", mScore); auto bestScoreLabel = Label::createWithSystemFont(score, "Consolas", 80); bestScoreLabel->setColor(Color3B(128, 0, 128)); bestScoreLabel->setPosition(Point(center.x, center.y + 20.0f)); sucessLayer->addChild(bestScoreLabel); sprintf(score, "BEST %d", mBestScoreCache); auto scoreLabel = Label::createWithSystemFont(score, "Consolas", 80); scoreLabel->setColor(Color3B(80, 160, 100)); scoreLabel->setPosition(Point(center.x, center.y - 100.0f)); sucessLayer->addChild(scoreLabel); getParent()->addChild(sucessLayer, 1); // setup touch event listener for sucessLayer, it swallows all touch events auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = [](Touch* touch, Event* event) -> bool { return true; }; touchListener->onTouchMoved = [] (Touch* touch, Event* event) {}; touchListener->onTouchCancelled = [] (Touch* touch, Event* event) {}; touchListener->onTouchEnded = [sucessLayer] (Touch* touch, Event* event) { sucessLayer->removeFromParent(); }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority( touchListener, sucessLayer); return true; } return false; }
void MainWindow::openover(){ if (isWin()==1){ isGameRun=0; windlg->setStyleSheet("QWidget { background-color: brown;border-style: outset; border-width: 2px;border-radius: 10px;border-color: beige;font: bold 14px;min-width: 10em;padding: 6px; }"); windlg->setModal(true); windlg->show(); } if (gameScore==0) {isGameRun=0; losedlg->setStyleSheet("QWidget { background-color: brown;border-style: outset; border-width: 2px;border-radius: 10px;border-color: beige;font: bold 14px;min-width: 10em;padding: 6px; }"); losedlg->setModal(true); losedlg->show(); } }
void GameScene::onTouchEnded(Touch* touch, Event* event) { if (isWin() || isGameOver()) { return; } GestureDetector::GestureType gesture = mGestureDetector.endPoint(touch->getLocation()); bool gestureValid = true; bool moved = false; switch (gesture) { case GestureDetector::MoveLeft: moved = moveLeft(); break; case GestureDetector::MoveRight: moved = moveRight(); break; case GestureDetector::MoveUp: moved = moveUp(); break; case GestureDetector::MoveDown: moved = moveDown(); break; case GestureDetector::Unknown: default: gestureValid = false; break; } if (gestureValid) { if (moved) { generateCard(true); CocosDenshion::SimpleAudioEngine::getInstance()->playEffect( MOVE_SUCESS_SOUND, false); } else { CocosDenshion::SimpleAudioEngine::getInstance()->playEffect( MOVE_FAILED_SOUND, false); } doCheck(); } }
void AiGame::mousePressEvent(QMouseEvent *event){ int x; int y; if(event->button() == Qt::LeftButton){ offset = event->pos();//获取鼠标的坐标 //棋盘区域 if(!win && offset.rx()>186&&offset.rx()<600&&offset.ry()>39&&offset.ry()<445) { if(chess[(offset.rx()-210)/27][(offset.ry()-60)/27])//如果鼠标点击的地方有旗子 return; x = (offset.rx()-210)/27; y = (offset.ry()-60)/27; if (offset.ry() > 415 && !chess[x][14])//补偿最后一格的误差 y = 14; clickcount++;//记录步数 movechess(x,y); win = isWin(x,y); ComMoveChess(); } } };
void GameBattle::update() { switch (state_) { case kStateStart: stateCounter_++; if (stateCounter_ > 60) { setState(firstAttack_? kStateFirstAttack : kStateMenu); } break; case kStateFirstAttack: stateCounter_++; if (stateCounter_ > 60) { setState(kStateMenu); } break; case kStateMenu: if (menu_.decided()) { switch (menu_.partyCommand()) { case GameBattleMenu::kPartyCommandManual: setState(kStateAnimation); break; case GameBattleMenu::kPartyCommandAuto: for (uint i = 0; i < players_.size(); i++) { players_[i]->setAttackInfoAuto(enemies_, players_, turnNum_); } setState(kStateAnimation); break; case GameBattleMenu::kPartyCommandEscape: setState(kStateEscape); break; } turnNum_++; } break; case kStateEscape: stateCounter_++; if (stateCounter_ > 60) { if (escapeSuccess_) { setState(kStateEnd); } else { for (uint i = 0; i < players_.size(); i++) { AttackInfo info; info.target = NULL; info.type = kAttackTypeNone; info.id = 0; players_[i]->setAttackInfo(info); } setState(kStateAnimation); } } break; case kStateAnimation: if (animationTargetIndex_ < 0) { if ((!skillAnime_ || skillAnime_->isFinished()) && !battleOrder_[currentAttacker_]->isAnimated()) { if (skillAnime_) { skillAnime_->release(); skillAnime_ = NULL; } if (animationTargetIndex_ < 0) { animationTargetIndex_ = 0; if (animationTargetIndex_ < (int)attackedTargets_.size()) { attackedTargets_[animationTargetIndex_]->playDamageAnime(); } } messageWindow_.setLineLimit(messageWindow_.lineLimit() + 1); } } else { if (animationTargetIndex_ < (int)attackedTargets_.size()) { if (!attackedTargets_[animationTargetIndex_]->isAnimated()) { if (attackedTargets_[animationTargetIndex_]->status().isDead() && !attackedTargets_[animationTargetIndex_]->isExcluded()) { attackedTargets_[animationTargetIndex_]->playDeadAnime(); } else { animationTargetIndex_++; if (animationTargetIndex_ < (int)attackedTargets_.size()) { attackedTargets_[animationTargetIndex_]->playDamageAnime(); } } messageWindow_.setLineLimit(messageWindow_.lineLimit() + 1); } } else { if (isLose()) { setState(kStateLose); } else if (isWin()) { setState(kStateResult); } else { currentAttacker_++; while (currentAttacker_ < (int)battleOrder_.size() && battleOrder_[currentAttacker_]->isExcluded()) { currentAttacker_++; } if (currentAttacker_ < (int)battleOrder_.size()) { stateCounter_ = 0; messageWindow_.reset(); setAnimationMessage(); } else { setState(kStateMenu); } } } } break; case kStateLose: stateCounter_++; if (messageWindow_.clicked()) { setState(kStateEnd); } break; case kStateResult: stateCounter_++; if (stateCounter_ > 20) { if (messageWindow_.lineLimit() < (int)messageWindow_.messageSize()) { messageWindow_.setLineLimit(messageWindow_.lineLimit() + 1); stateCounter_ = 0; } else { messageWindow_.enableClick(); if (messageWindow_.clicked()) { setState(kStateEnd); } } } break; case kStateEnd: break; } }
void MiniMax::scoreState(tree& state) { /* Score the given state */ int m = state.board.size(); // num columns int n = state.board[0].length() - 1; // num rows int R = state.R; // for my convenience int d = ((m - R) + (n - R) + 1); // num diags (usable) int s = n - R; // anchor point for diags int score = 0; // the score we will assign std::vector<std::string> rows; // board rows std::vector<std::string> diaD; // board down diags (usable) std::vector<std::string> diaU; // board up diags (usable) // this prevents multiple resize operations and initializes all values // in each vector rows.resize(n); diaD.resize(d); diaU.resize(d); // fill in rows, diaD, and diaU for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { rows[j] += state.board[i][j]; if ((-1 * s) - (m - n) <= (j - i) && (j - i) <= s) { // up diags diaU[s - (j - i)] += state.board[i][j]; } if (s < (i + j) && (i + j) < (s + d)) { // down diags diaD[(i + j) - (s + 1)] += state.board[i][j]; } } } int col = state.move; if (col < 0 || col >= (int) state.board.size()) { state.score = 0; return; } int row = state.board[col].find_last_of("XO"); int diU = s - (col - row); int diD = (col + row) - (s + 1); std::string c = state.board[col]; std::string r = rows[row]; char placed = c.at(row); bool blocked = false; std::string D; if (diD >= 0 && diD < (int) diaD.size()) { D = diaD[diD]; int x = (col + row >= s + R) ? col - ((col + row) - n) : col; blocked |= checkblock(D, placed, x, R); } std::string U; if (diU >=0 && diU < (int) diaU.size()) { U = diaU[diU]; int x = (col - row >= 1) ? col - (col - row) : col; blocked |= checkblock(U, placed, x, R); } blocked |= ( checkblock(c, placed, row, R) || checkblock(r, placed, col, R) ); if (blocked) { state.score = (placed == 'X') ? std::numeric_limits<int>::max() - 2 : std::numeric_limits<int>::min() + 2; return; } // score all the things for (std::string& column : state.board) { int s = scoreLine(column, R); if (isWin(s)) { state.score = s; return; } score += s; } for (std::string& row : rows) { int s = scoreLine(row, R); if (isWin(s)) { state.score = s; return; } score += s; } for (std::string& diag : diaD) { int s = scoreLine(diag, R); if (isWin(s)) { state.score = s; return; } score += s; } for (std::string& diag : diaU) { int s = scoreLine(diag, R); if (isWin(s)) { state.score = s; return; } score += s; } state.score = score; }
int main() { REG_DISPCTL = MODE3 | BG2_ENABLE; //Draw Start Screen drawImage3(0, 0, TITLESCREEN_WIDTH, TITLESCREEN_HEIGHT, titleScreen); //var to keep track of current position in game int inGame = 0; int inTitle = 1; while(1) { //START GAME if(inTitle == 1 && KEY_DOWN_NOW(BUTTON_START)) { inGame = 1; inTitle = 0; int bgcolor = GRAY; DMA[3].src = &bgcolor; DMA[3].dst = videoBuffer; DMA[3].cnt = 38400 | DMA_SOURCE_FIXED | DMA_DESTINATION_INCREMENT | DMA_ON; drawLevel1Board(); refillLives(); resetBoard(); } //JUMP BACK TO TITLE SCREEN if(KEY_DOWN_NOW(BUTTON_SELECT)) { inGame = 0; inTitle = 1; drawImage3(0, 0, TITLESCREEN_WIDTH, TITLESCREEN_HEIGHT, titleScreen); } //GAME PLAY if(inGame == 1) { if(KEY_DOWN_NOW(BUTTON_RIGHT)) { moveRight(); } else if(KEY_DOWN_NOW(BUTTON_LEFT)) { moveLeft(); } else if(KEY_DOWN_NOW(BUTTON_UP)) { moveUp(); } else if(KEY_DOWN_NOW(BUTTON_DOWN)) { moveDown(); } waitForVblank(); clearOld(); drawCurr(); //test if reach end of level if(isWin() == 1) { drawImage3(0, 0, YOUWIN_WIDTH, YOUWIN_HEIGHT, youwin); inGame = 0; inTitle = 0; } //test for Collisions with Enemies if(isCollide() > 0) { if(currLives() > 0) { resetBoard(); } else { //out of lives = game over inGame = 0; inTitle = 0; drawImage3(0, 0, GAMEOVER_WIDTH, GAMEOVER_HEIGHT, gameover); } } } } return 0; }
int alphaBeta(int depth, int alpha, int beta, bool whiteToPlay) { int val, i; EVALUATE_INFO_t eval = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint32_t legalMoves = 0; PIECE_t pieceBackup; PIECE_e piece; #if ENABLE_TRANSPOSITION_TABLE int hashFlag = ALPHA_HASH_RESULT; if (val = probeHash(depth, alpha, beta) != UNKNOWN_HASH_RESULT) { cacheHits++; return val; } else { cacheMisses++; } #endif // ENABLE_TRANSPOSITION_TABLE // calculate all of the moves MOVE_t moves[MOVE_LIST_SIZE]; legalMoves += AddAllLegalMovesToMoveList(moves, &eval, whiteToPlay); if (!legalMoves && depth == currentDepth) { printf("pass"); exit(0); } if (depth == 0) { numberEvaluations++; AddAllLegalMovesToMoveList(&moves[legalMoves-1], &eval, !whiteToPlay); val = evaluateBoard(&eval); #if ENABLE_TRANSPOSITION_TABLE recordHash(depth, val, EXACT_HASH_RESULT); #endif //ENABLE_TRANSPOSITION_TABLE if (!whiteToPlay) val = val * -1; return val; } numberNodes++; // for each move for (i = 0; i < legalMoves; i++) { // backup piece so we can undo the move later piece = (moves[i].move & PIECE_MASK) >> PIECE_SHIFT; pieceBackup.piece = pieces[piece].piece; // play the move playMove(moves, i); // Check to see if this position is a win val = isWin(); if (!whiteToPlay) { val = val*-1; } if (val > DRAW_SCORE) { val = val + depth; } else if (val < 0) { val = val - depth; } else if (val == DRAW_SCORE) { val = 0; } else { // not a win or draw; search deeper //val = alphaBeta(depth - 1, alpha, beta, !whiteToPlay); val = -alphaBeta(depth - 1, -beta, -alpha, !whiteToPlay); } // undo move undoMove(pieceBackup, piece); // alpha beta pruning: if (val >= beta) { #if ENABLE_TRANSPOSITION_TABLE recordHash(depth, beta, BETA_HASH_RESULT); #endif //ENABLE_TRANSPOSITION_TABLE return beta; } if (val > alpha) { alpha = val; if (depth == currentDepth) { currMove.move = moves[i].move; currentScore = val; } #if ENABLE_TRANSPOSITION_TABLE hashFlag = EXACT_HASH_RESULT; #endif //ENABLE_TRANSPOSITION_TABLE } } #if ENABLE_TRANSPOSITION_TABLE recordHash(depth, alpha, hashFlag); #endif //ENABLE_TRANSPOSITION_TABLE return alpha; }
int main(){ int i,j; bool mark; int n =8; fillBox(n); fillBox(n); output(n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); printf("%d\n",myrandom() % n); while (true){ char ch; scanf("%c%*c", &ch); if (ch == 'a'){ // mark = left(n); left_remove_blank(n); left(n); } else if (ch == 'd'){ // mark = right(n); right_remove_blank(n); right(n); } else if (ch == 'w'){ // mark = up(n); up_remove_blank(n); up(n); } else if (ch == 's'){ // mark = down(n); down_remove_blank(n); down(n); } else{ continue; } system("clear"); //printf("Move:\n"); //output(); // if (!mark){ // continue; // } fillBox(n); printf("Fill:\n"); output(n); if (isOver(n)){ printf("\n\nGame Over!\n\n"); break; } if (isWin(n)) { printf("\n\n Wow You Win!\n\n"); break; /* code */ } } return 0; }
void GameField::handleEvent(SDL_Event* event, SmileBar* smileBar) { if (gameState != GameState::IN_PROGRESS && gameState != GameState::INIT) { return; } int x = (event->button).x; int y = (event->button).y; const SDL_Rect* clip = cfg->getClip(Clip::CELL_INIT); size_t row = (y - topBarHeight) / clip->h; size_t col = x / clip->w; auto btnType = (event->button).button; if (event->type == SDL_MOUSEBUTTONDOWN) { if (insideField(x, y)) { if (gameState == GameState::INIT) { gameState = GameState::IN_PROGRESS; smileBar->startTimer(); } pressedRow = row; pressedCol = col; switch (front[pressedRow][pressedCol]) { case Clip::CELL_INIT: front[pressedRow][pressedCol] = Clip::CELL_PRESSED; if (btnType == SDL_BUTTON_LEFT) { smileBar->smileState = Clip::SMILE_WONDER; } break; case Clip::CELL_FLAG: front[pressedRow][pressedCol] = Clip::CELL_FLAG_PRESSED; break; case Clip::CELL_QM: front[pressedRow][pressedCol] = Clip::CELL_QM_PRESSED; break; default: pressedRow = INF; pressedCol = INF; break; } } } else if (event->type == SDL_MOUSEBUTTONUP) { if (pressedRow < INF && pressedCol < INF) { switch (front[pressedRow][pressedCol]) { case Clip::CELL_FLAG_PRESSED: if (btnType == SDL_BUTTON_LEFT) { front[pressedRow][pressedCol] = Clip::CELL_FLAG; } if (btnType == SDL_BUTTON_RIGHT) { front[pressedRow][pressedCol] = Clip::CELL_QM; smileBar->incrMines(); } break; case Clip::CELL_QM_PRESSED: if (btnType == SDL_BUTTON_LEFT) { front[pressedRow][pressedCol] = Clip::CELL_QM; } else if (btnType == SDL_BUTTON_RIGHT) { front[pressedRow][pressedCol] = Clip::CELL_INIT; } break; case Clip::CELL_PRESSED: if (btnType == SDL_BUTTON_LEFT) { switch (back[pressedRow][pressedCol]) { case Clip::CELL_PRESSED: smileBar->smileState = Clip::SMILE_INIT; openEmptyCells(); break; case Clip::CELL_MINE: smileBar->smileState = Clip::SMILE_LOSE; openAllCells(); break; default: smileBar->smileState = Clip::SMILE_INIT; front[pressedRow][pressedCol] = back[pressedRow][pressedCol]; break; } } else if (btnType == SDL_BUTTON_RIGHT) { front[pressedRow][pressedCol] = Clip::CELL_FLAG; smileBar->decrMines(); } break; default: break; } pressedRow = INF; pressedCol = INF; } } if (isWin()) { gameState = GameState::WIN; smileBar->smileState = Clip::SMILE_WIN; openAllFlags(); } if (gameState == GameState::WIN || gameState == GameState::LOSE) { smileBar->stopTimer(); } }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("Simon Project 1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL); // SDL Window, title, position,position,width,height, type of graphics? SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); glClearColor(0.5, 0.5, 0.0, .9);//Green-color //Setup glViewport(0, 0, 800, 600); glMatrixMode(GL_PROJECTION); glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0); //LoadTextures GLuint paddleID = LoadTexture("pngs/paddle.png"); GLuint ballID = LoadTexture("pngs/ball.png"); GLuint leftwinID = LoadTexture24("pngs/leftwin.png"); GLuint rightwinID = LoadTexture24("pngs/rightwin.png"); //Init Entities initBall(ballID); initPaddleLeft(paddleID); initPaddleRight(paddleID); initRightwin(rightwinID); initLeftwin(leftwinID); //Time float lastFrameTicks = 0.0; SDL_Event event; bool done = false; while (!done) { glClear(GL_COLOR_BUFFER_BIT); float ticks = (float)SDL_GetTicks() / 1000.0f; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; //Read Input and Update World while (SDL_PollEvent(&event)) { // a lot of events could cue up, no?, could also get all keyboard states and check for those. I think I like that better. - specially for pong if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } const Uint8 *keys = SDL_GetKeyboardState(NULL); if (keys[SDL_SCANCODE_UP]) { paddleright.y += elapsed*paddleright.velocity_y; if (paddleright.y > (1 - .2)){ paddleright.y = 1 - .2; } } else if (keys[SDL_SCANCODE_DOWN]) { paddleright.y -= elapsed*paddleright.velocity_y; if (paddleright.y < (-1 + .2)){ paddleright.y = -1 + .2; } } if (keys[SDL_SCANCODE_W]) { paddleleft.y += elapsed*paddleleft.velocity_y; if (paddleleft.y >(1 - .2)){ paddleleft.y = 1 - .2; } } else if (keys[SDL_SCANCODE_S]) { paddleleft.y -= elapsed*paddleleft.velocity_y; if (paddleleft.y < (-1 + .2)){ paddleleft.y = -1 + .2; } } updateBall(elapsed); isWin(); //Render World ball.Draw(); paddleleft.Draw(); paddleright.Draw(); if (rightwin) { endGame(); rightwinE.Draw(); } if (leftwin) { endGame(); leftwinE.Draw(); } SDL_GL_SwapWindow(displayWindow);//Swaps old modelview with new one? } SDL_Quit(); return 0; }