Пример #1
0
void ConnectFour::run(){
	if(controller->buttonPressed(controller->BUTTON_SELECT) && !controller->buttonHandled(controller->BUTTON_SELECT)){
		controller->handleButton(controller->BUTTON_SELECT);
		newGame();
	}
	if(winner==0){
		if(dropHeight<8){
			//droppedPieces[dropPos][dropHeight-1]
			if(dropHeight>=2 && (dropHeight==7 || droppedPieces[dropPos][dropHeight-2]==0)){
				dropHeight--;
			}else{
				droppedPieces[dropPos][dropHeight-1] = curPlayer;
				dropHeight=8;
				//check winner

				for(int xPos=0;xPos<7;xPos++){
					for(int yPos=0;yPos<3;yPos++){
						if(droppedPieces[xPos][yPos]==curPlayer &&
								droppedPieces[xPos][yPos+1]==curPlayer &&
								droppedPieces[xPos][yPos+2]==curPlayer &&
								droppedPieces[xPos][yPos+3]==curPlayer){
							winner=curPlayer;
							winPos[0].setPosition(xPos,yPos);
							winPos[1].setPosition(xPos,yPos+1);
							winPos[2].setPosition(xPos,yPos+2);
							winPos[3].setPosition(xPos,yPos+3);
							winTime = millis();
						}
					}
				}
				for(int xPos=0;xPos<4;xPos++){
					for(int yPos=0;yPos<6;yPos++){
						if(droppedPieces[xPos][yPos]==curPlayer &&
								droppedPieces[xPos+1][yPos]==curPlayer &&
								droppedPieces[xPos+2][yPos]==curPlayer &&
								droppedPieces[xPos+3][yPos]==curPlayer){
							winner=curPlayer;
							winPos[0].setPosition(xPos,yPos);
							winPos[1].setPosition(xPos+1,yPos);
							winPos[2].setPosition(xPos+2,yPos);
							winPos[3].setPosition(xPos+3,yPos);
							winTime = millis();
						}
					}
				}
				for(int xPos=0;xPos<4;xPos++){
					for(int yPos=0;yPos<3;yPos++){
						if(droppedPieces[xPos][yPos]==curPlayer &&
								droppedPieces[xPos+1][yPos+1]==curPlayer &&
								droppedPieces[xPos+2][yPos+2]==curPlayer &&
								droppedPieces[xPos+3][yPos+3]==curPlayer){
							winner=curPlayer;
							winPos[0].setPosition(xPos,yPos);
							winPos[1].setPosition(xPos+1,yPos+1);
							winPos[2].setPosition(xPos+2,yPos+2);
							winPos[3].setPosition(xPos+3,yPos+3);
							winTime = millis();
						}
					}
				}
				for(int xPos=0;xPos<4;xPos++){
					for(int yPos=3;yPos<6;yPos++){
						if(droppedPieces[xPos][yPos]==curPlayer &&
								droppedPieces[xPos+1][yPos-1]==curPlayer &&
								droppedPieces[xPos+2][yPos-2]==curPlayer &&
								droppedPieces[xPos+3][yPos-3]==curPlayer){
							winner=curPlayer;
							winPos[0].setPosition(xPos,yPos);
							winPos[1].setPosition(xPos+1,yPos-1);
							winPos[2].setPosition(xPos+2,yPos-2);
							winPos[3].setPosition(xPos+3,yPos-3);
							winTime = millis();
						}
					}
				}
				curPlayer=(curPlayer)%2+1;
				updateDisplay();
			}
			redrawBoard();
		}else{
			if(controller->buttonPressed(controller->BUTTON_LEFT) && !controller->buttonHandled(controller->BUTTON_LEFT)){
				controller->handleButton(controller->BUTTON_LEFT);
				dropPos--;
				if(dropPos<0){
					dropPos=6;
				}
				redrawBoard();
			}
			if(controller->buttonPressed(controller->BUTTON_RIGHT) && !controller->buttonHandled(controller->BUTTON_RIGHT)){
				controller->handleButton(controller->BUTTON_RIGHT);
				dropPos=(dropPos+1)%7;
				redrawBoard();
			}
			if(controller->buttonPressed(controller->BUTTON_A) && !controller->buttonHandled(controller->BUTTON_A)){
				controller->handleButton(controller->BUTTON_A);
				if(dropHeight==8 && droppedPieces[dropPos][5]==0){
					dropHeight--;
					redrawBoard();
				}
			}
		}
	}else{
		redrawBoard();
	}
}
int main(int argc, char** argv){

  //srand(time(NULL));

  struct gameState *p = newGame();

	int a, b, c, d, gs, k[10];
  int ActCardVal, numPlayers, cardPos;
	char *cardTitle;
  char card_string[32];


  for (a=0 ; a < MAX_TESTS ; a++){

      printf("\n************************** STARTING GAME %i **************************\n\n", a+1);

      // RANDOMIZE NUMBER OF PLAYERS ------------------------
      numPlayers = (rand() % 3) + 2; // 2-4 Players


      // RANDOMIZE KINGDOM CARDS ----------------------------
      printf("KingdomCards: \n");
      for (b=0 ; b<10 ; b++){
        ActCardVal = (rand()%20)+7;
        c=0;
        while (c<b){ // check previous actions cards
          if (k[c]==ActCardVal){
            ActCardVal = (rand()%20)+7;
            c=0;
          }
          c++;
        }
        k[b]=ActCardVal;
        cardNumToName(k[b],card_string);
        printf( "%d --> %s (%i) \n" , b+1 , card_string, ActCardVal);
      }
      printf("\n");


      // INITIALIZE GAME ------------------------------------
      gs = initializeGame(numPlayers, k, 2, p);

      int money = 0;
      int smithyPos = -1;
      int adventurerPos = -1;
      int i=0;

      int numSmithies = 0;
      int numAdventurers = 0;

      while (!isGameOver(p))
		{
			printf("------------------------------------------\n");
			money = 0;
			smithyPos = -1;
			adventurerPos = -1;
			for (i = 0; i < numHandCards(p); i++)
			{
				if (handCard(i, p) == copper)
					money++;
				else if (handCard(i, p) == silver)
					money += 2;
				else if (handCard(i, p) == gold)
					money += 3;
				else if (handCard(i, p) == smithy)
					smithyPos = i;
				else if (handCard(i, p) == adventurer)
					adventurerPos = i;
			}

			if ((rand() % 5) == 0)		
			{
				if (smithyPos != -1)
				{
					printf("Player %i: smithy (%i) played from position %i\n", whoseTurn(p), ActCardVal, smithyPos);
					playCard(smithyPos, -1, -1, -1, p);
					if (ActCardVal < 0 || ActCardVal > 26) {
						printf("--> Card play failed\n");
					} else {
            printf("--> Card play successful\n");
          }

					money = 0;
					i = 0;
					while (i<numHandCards(p))
					{
						if (handCard(i, p) == copper)
						{
							playCard(i, -1, -1, -1, p);
							money++;
						}
						else if (handCard(i, p) == silver)
						{
							playCard(i, -1, -1, -1, p);
							money += 2;
						}
						else if (handCard(i, p) == gold)
						{
							playCard(i, -1, -1, -1, p);
							money += 3;
						}
						i++;
					}
				}

				if (money >= 8)
				{
					printf("Player %i: bought province\n", whoseTurn(p));
					buyCard(province, p);
				}
				else if (money >= 6)
				{
					printf("Player %i: bought gold\n", whoseTurn(p));
					buyCard(gold, p);
				}
				else if ((money >= 4) && (numSmithies < 2))
				{
					printf("Player %i: bought smithy\n", whoseTurn(p));
					buyCard(smithy, p);
					numSmithies++;
				}
				else if (money >= 3)
				{
					printf("Player %i: bought silver\n", whoseTurn(p));
					buyCard(silver, p);
				}

				printf("Player %i: end turn\n", whoseTurn(p));
				endTurn(p);
			}
			else if ((rand() % 5) == 1)
			{
				if (adventurerPos != -1)
				{
					printf("Player %i: adventurer (%i) played from position %i\n", whoseTurn(p), ActCardVal, adventurerPos);
					gs = playCard(adventurerPos, -1, -1, -1, p);
					if (ActCardVal < 0 || ActCardVal > 26)
					{
						printf("--> Card play failed!\n");
					} else {
            printf("--> Card play successful\n");
          }

				}

				money = 0;
				i = 0;
				while (i<numHandCards(p))
				{
					if (handCard(i, p) == copper)
					{
						playCard(i, -1, -1, -1, p);
						money++;
					}
					else if (handCard(i, p) == silver)
					{
						playCard(i, -1, -1, -1, p);
						money += 2;
					}
					else if (handCard(i, p) == gold)
					{
						playCard(i, -1, -1, -1, p);
						money += 3;
					}
					i++;
				}

				if (money >= 8)
				{
					printf("Player %i: bought province\n", whoseTurn(p));
					buyCard(province, p);
				}
				else if ((money >= 6) && (numAdventurers < 2))
				{
					printf("Player %i: bought adventurer\n", whoseTurn(p));
					buyCard(adventurer, p);
					numAdventurers++;
				}
				else if (money >= 6)
				{
					printf("Player %i: bought gold\n", whoseTurn(p));
					buyCard(gold, p);
				}
				else if (money >= 3)
				{
					printf("Player %i: bought silver\n", whoseTurn(p));
					buyCard(silver, p);
				}
				printf("Player %i: endTurn\n", whoseTurn(p));
				endTurn(p);
			}
			else
			{
				cardPos = rand() % numHandCards(p);
				ActCardVal = p->hand[whoseTurn(p)][cardPos];
				cardTitle = print_card_name(ActCardVal);
				printf("Player %i: %s (%i) played from %i\n", whoseTurn(p), cardTitle, ActCardVal, cardPos);
				gs = playCard(ActCardVal, rand() % numHandCards(p), rand() % numHandCards(p), rand() % numHandCards(p), p);
				if (ActCardVal < 0 || ActCardVal > 26)
				{
					printf("--> Card play failed!\n");
				} else {
          printf("--> Card play successful\n");
        }

				money = 0;
				i = 0;
				while (i<numHandCards(p))
				{
					if (handCard(i, p) == copper)
					{
						playCard(i, -1, -1, -1, p);
						money++;
					}
					else if (handCard(i, p) == silver)
					{
						playCard(i, -1, -1, -1, p);
						money += 2;
					}
					else if (handCard(i, p) == gold)
					{
						playCard(i, -1, -1, -1, p);
						money += 3;
					}
					i++;
				}

				if (money >= 8)
				{
					printf("Player %i: bought province\n", whoseTurn(p));
					buyCard(province, p);
				}
				else if ((money >= 6) && (numAdventurers < 2))
				{
					printf("Player %i: bought adventurer\n", whoseTurn(p));
					buyCard(adventurer, p);
					numAdventurers++;
				}
				else if (money >= 6)
				{
					printf("Player %i: bought gold\n", whoseTurn(p));
					buyCard(gold, p);
				}
				else if (money >= 3)
				{
					printf("Player %i: bought silver\n", whoseTurn(p));
					buyCard(silver, p);
				}
				printf("Player %i: endTurn\n", whoseTurn(p));
				endTurn(p);

			}
		}

    printf ("\n###################\n# FINAL SCORE \n");
    int tempScore;
    for (d=0 ; d<numPlayers ; d++){
      tempScore = scoreFor(d,p);
      printf("# Player %i: %i\n", d,tempScore);
    }
    printf ("###################\n\n");
	}

	return 0;

}
Пример #3
0
/**
 * Creates a new game in Experienced difficulty and
 * jumps to the Geoscape screen.
 * @param action Pointer to an action.
 */
void NewGameState::btnExperiencedClick(Action *action)
{
	newGame(DIFF_EXPERIENCED);
}
Пример #4
0
	void init() {
		debug::log("I know you're going to dig this");
		newGame();
	}
Пример #5
0
Window::Window(QWidget *parent, Qt::WindowFlags wf)
:	QMainWindow(parent, wf)
{
	QWidget* contents = new QWidget(this);
	setCentralWidget(contents);

	// Create preview
	m_preview = new QLabel(contents);
	m_preview->setFixedSize(80, 100);
	m_preview->setAutoFillBackground(true);
	{
		QPalette palette = m_preview->palette();
		palette.setColor(m_preview->backgroundRole(), Qt::black);
		m_preview->setPalette(palette);
	}

	// Create level display
	m_level = new QLabel("0", contents);
	m_level->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
	m_level->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
	m_level->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);

	// Create lines display
	m_lines = new QLabel("0", contents);
	m_lines->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
	m_lines->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
	m_lines->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);

	// Create score display
	m_score = new QLabel("0", contents);
	m_score->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
	m_score->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
	m_score->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);

	// Create scoreboard
	m_score_board = new ScoreBoard(this);

	// Create board
	m_board = new Board(contents);
	connect(m_board, &Board::pauseAvailable, this, &Window::pauseAvailable);
	connect(m_board, &Board::nextPieceAvailable, m_preview, &QLabel::setPixmap);
	connect(m_board, &Board::levelUpdated, m_level, static_cast<void (QLabel::*)(int)>(&QLabel::setNum));
	connect(m_board, &Board::linesRemovedUpdated, m_lines, static_cast<void (QLabel::*)(int)>(&QLabel::setNum));
	connect(m_board, &Board::scoreUpdated, this, &Window::scoreUpdated);
	connect(m_board, static_cast<void (Board::*)(int,int,int)>(&Board::gameOver), m_score_board, &ScoreBoard::addHighScore);
	connect(m_board, static_cast<void (Board::*)(int,int,int)>(&Board::gameOver), this, &Window::gameOver);
	connect(m_board, &Board::gameStarted, this, &Window::newGame);

	// Create overlay message
	QLabel* message = new QLabel(tr("Click to start a new game."), contents);
	message->setAttribute(Qt::WA_TransparentForMouseEvents);
	message->setAlignment(Qt::AlignCenter);
	message->setStyleSheet(
		"QLabel {"
			"background-color: rgba(255, 255, 255, 200);"
			"color: black;"
			"margin: 0;"
			"padding: 0.5em;"
			"border-radius: 0.5em;"
		"}");
	message->setWordWrap(true);
	connect(m_board, &Board::showMessage, message, &QLabel::show);
	connect(m_board, &Board::showMessage, message, &QLabel::setText);
	connect(m_board, &Board::hideMessage, message, &QLabel::hide);
	connect(m_board, &Board::hideMessage, message, &QLabel::clear);

	// Create menus
	QMenu* menu = menuBar()->addMenu(tr("&Game"));
	menu->addAction(tr("&New"), m_board, SLOT(newGame()), QKeySequence::New);
	m_pause_action = menu->addAction(tr("&Pause"), m_board, SLOT(pauseGame()), tr("P"));
	m_pause_action->setEnabled(false);
	m_resume_action = menu->addAction(tr("&Resume"), m_board, SLOT(resumeGame()), tr("P"));
	m_resume_action->setVisible(false);
	menu->addSeparator();
	menu->addAction(tr("&Scores"), m_score_board, SLOT(show()));
	menu->addSeparator();
	QAction* action = menu->addAction(tr("&Quit"), this, SLOT(close()), QKeySequence::Quit);
	action->setMenuRole(QAction::QuitRole);

	menu = menuBar()->addMenu(tr("&Settings"));
	menu->addAction(tr("Application &Language..."), this, SLOT(setLocale()));

	menu = menuBar()->addMenu(tr("&Help"));
	action = menu->addAction(tr("&About"), this, SLOT(about()));
	action->setMenuRole(QAction::AboutRole);
	action = menu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
	action->setMenuRole(QAction::AboutQtRole);

	// Layout window
	QGridLayout* layout = new QGridLayout(contents);
	layout->setMargin(12);
	layout->setSpacing(0);
	layout->setColumnStretch(0, 1);
	layout->setColumnMinimumWidth(1, 12);
	layout->setRowStretch(11, 1);
	layout->setRowMinimumHeight(2, 24);
	layout->setRowMinimumHeight(5, 24);
	layout->setRowMinimumHeight(8, 24);
	layout->addWidget(m_board, 0, 0, 12, 1);
	layout->addWidget(message, 0, 0, 12, 1, Qt::AlignCenter);
	layout->addWidget(new QLabel(tr("Next Piece"), contents), 0, 2, 1, 1, Qt::AlignCenter);
	layout->addWidget(m_preview, 1, 2, Qt::AlignCenter);
	layout->addWidget(new QLabel(tr("Level"), contents), 3, 2, 1, 1, Qt::AlignCenter);
	layout->addWidget(m_level, 4, 2);
	layout->addWidget(new QLabel(tr("Removed Lines"), contents), 6, 2, 1, 1, Qt::AlignCenter);
	layout->addWidget(m_lines, 7, 2);
	layout->addWidget(new QLabel(tr("Score"), contents), 9, 2, 1, 1, Qt::AlignCenter);
	layout->addWidget(m_score, 10, 2);

	// Restore window
	restoreGeometry(QSettings().value("Geometry").toByteArray());
}
Пример #6
0
void Game::menu()
{

    game = new QPopupMenu();
    CHECK_PTR( game );
    game->insertItem( klocale->translate("New"), this, SLOT(newGame()),Key_F2);
    pauseID = game->insertItem( klocale->translate("Pause"), this , SLOT(pauseGame()), Key_F3);
    game->insertItem( klocale->translate("High Scores..."), this, SLOT(showHighScores()));
    game->insertSeparator();
    game->insertItem( klocale->translate("&Quit"),  this, SLOT(quitGame()), CTRL+Key_Q );
    game->setCheckable( TRUE );

    balls = new QPopupMenu;
    CHECK_PTR( balls );
    ballsID[0] = balls->insertItem( klocale->translate("0"));
    ballsID[1] = balls->insertItem( klocale->translate("1"));
    ballsID[2] = balls->insertItem( klocale->translate("2"));
    ballsID[3] = balls->insertItem( klocale->translate("3"));
    balls->setCheckable( TRUE );
    connect(balls, SIGNAL(activated(int)), this, SLOT ( ballsChecked(int) ));

    snakes = new QPopupMenu;
    CHECK_PTR( snakes );
    snakesID[0] = snakes->insertItem( klocale->translate("0"));
    snakesID[1] = snakes->insertItem( klocale->translate("1"));
    snakesID[2] = snakes->insertItem( klocale->translate("2"));
    snakesID[3] = snakes->insertItem( klocale->translate("3"));
    snakes->setCheckable( TRUE );
    connect(snakes, SIGNAL(activated(int)), this,
	    SLOT ( snakesChecked(int) ));


    pix = new QPopupMenu;
    lookupBackgroundPixmaps();
    pixID.resize(backgroundPixmaps.count());

    if(backgroundPixmaps.count() == 0)
	pix->insertItem(klocale->translate("none"));
    else
	for(unsigned i = 0; i < backgroundPixmaps.count(); i++) {
	    // since the filename may contain underscore, they
	    // are replaced with spaces in the menu entry
	    QString s(backgroundPixmaps.at(i)->baseName());
	    s = s.replace(QRegExp("_"), " ");
	    pixID[i] = pix->insertItem((const char *)s);
	}
    pix->setCheckable( TRUE );
    connect(pix, SIGNAL(activated(int)), this,
	    SLOT ( pixChecked(int) ));

    options = new QPopupMenu();
    CHECK_PTR( options );
    skillID[0] = options->insertItem( klocale->translate("Beginner"));
    skillID[1] = options->insertItem( klocale->translate("Intermediate"));
    skillID[2] = options->insertItem( klocale->translate("Advanced"));
    skillID[3] = options->insertItem( klocale->translate("Expert"));
    options->insertSeparator();
    options->insertItem(klocale->translate("Balls"), balls);
    options->insertItem(klocale->translate("Computer Snakes"), snakes);
    options->insertSeparator();
    options->insertItem(klocale->translate("Select background color..."), this, SLOT(backgroundColor()));
    options->insertItem(klocale->translate("Select background pixmap"), pix);
    options->insertSeparator();
    options->insertItem(klocale->translate("Change keys..."),this, SLOT(confKeys()));
    options->insertSeparator();
    options->insertItem(klocale->translate("Starting Room..."), this, SLOT(startingRoom()));

    options->setCheckable( TRUE );
    connect(options, SIGNAL(activated(int)), this, SLOT ( skillChecked(int) ));

    QPopupMenu *help = kapp->getHelpMenu(true, QString(klocale->translate("Snake Race"))
                                         + " " + KSNAKE_VERSION
                                         + klocale->translate("\n\nby Michel Filippi"
                                         " ([email protected])")); 
    menubar = new KMenuBar( this );
    CHECK_PTR( menubar );
    menubar->insertItem( klocale->translate("&Game"), game );
    menubar->insertItem( klocale->translate("&Options"), options );
    menubar->insertSeparator();
    menubar->insertItem( klocale->translate("&Help"), help);
}
Пример #7
0
int main(int argc, char * argv[]) 
{

  Game game = {FALSE, 0};
  char guesses[80];
  int wordLength;
  int dashes;
  int incorrectGuesses;
  int maxTries;

  while(game.gameOver == FALSE)
  {
    char * word;
    char * ptr;
   	wordLength = 0;
    dashes = 0;
    incorrectGuesses = 0;
    maxTries = 15;
	  wordLength = selectWord(game.randomWord);        /* Selecting random word */
	  word = game.randomWord;                          /* Assigning word  to the randomWord */
    ptr = strchr(word,'\n');                           /* Getting rid of the new line */ 
    *ptr = '\0';

    for (dashes = 0; dashes < wordLength; dashes ++)  /* For loop to print out the dashes */
    {
      guesses[dashes] = DASH;
    }
  
    printWelcomeMessages( wordLength );
	
    char input;
	
    while(game.gameOver == FALSE)
	  {
			
      printf("Number of guesses: %i\n",incorrectGuesses);
      printf("Number of tries left: %i\n",(maxTries - incorrectGuesses));
			printLettersGuessed( &game, game.totalGuesses );
		  printf( "Guess a letter: ");
			scanf( " %c", &input );

      if (input == '\n' || input == ' ')
      {
        input = getchar();
      }
			game.lettersGuessed[game.totalGuesses] = input;
			game.totalGuesses++;
      if (compareChar(input,word,guesses))
      {
        printf("\n\nYou guessed '%c' correctly\n\n",input);
      }
      else
      {
        printf("\n\nSorry, '%c' is not a letter in the word\n\n",input);
				incorrectGuesses++;
      }

      printChar(guesses,wordLength);
      if (!gameOver(game.numRight,wordLength,guesses))
      {
				system("clear");
        printf("Congratulations! You have correctly guessed '%s'!\n\n",guesses);
        break;
      }
      if (incorrectGuesses == maxTries)
      {
				system("clear");
        printf("GAME OVER!\nYou have failed to guess '%s'\n\n",word);
        break;
      }
      
	  }

    newGame(game,guesses);
  }
	return 0;
}
Пример #8
0
// on "init" you need to initialize your instance
bool SnakeGame::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "arrow.png",
                                           "arrow_clicked.png",
                                           CC_CALLBACK_1(SnakeGame::menuCloseCallback, this));
    
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

	//score
	score_label = Label::createWithTTF("Score: 0", "fonts/Marker Felt.ttf", 24);
	score_label->setColor(Color3B(0, 0, 0));
	score_label->setPosition(Vec2(score_label->getContentSize().width / 2 + 10,
		origin.y + visibleSize.height - score_label->getContentSize().height));
	this->addChild(score_label, 1);
	
	//high score
	high_score_label = Label::createWithTTF("High Score: 0", "fonts/Marker Felt.ttf", 24);
	high_score_label->setColor(Color3B(0, 0, 0));
	high_score_label->setPosition(Vec2(origin.x + visibleSize.width - high_score_label->getContentSize().width / 2 - 10,
		origin.y + visibleSize.height - high_score_label->getContentSize().height));
	this->addChild(high_score_label, 1);

	drawBackground();

	apple = Sprite::create("snakes.png", Rect(0, SPRITE_HEIGHT * 3, SPRITE_WIDTH, SPRITE_HEIGHT));
	apple->setAnchorPoint(Vec2(0, 0));
	this->addChild(apple);

	iPhone = Sprite::create("phone.png");
	iPhone->setAnchorPoint(Vec2(0, 0));
	this->addChild(iPhone);

	mac = Sprite::create("mac.png");
	mac->setAnchorPoint(Vec2(0, 0));
	this->addChild(mac);

	srand(time(NULL));

	newGame();

	this->scheduleUpdate();

	// creating a keyboard event listener
	auto listener = EventListenerKeyboard::create();
	listener->onKeyPressed = CC_CALLBACK_2(SnakeGame::onKeyPressed, this);
	listener->onKeyReleased = CC_CALLBACK_2(SnakeGame::onKeyReleased, this);

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    return true;
}
Пример #9
0
void SnakeGame::update(float dt)
{
	
	if (speed_counter == speed)
	{
		Vec2 p = snake.at(0)->getPosition();

		int x = p.x;
		int y = p.y;

		switch (direction){
			case 1:
				y += SPRITE_HEIGHT;
				break;
			case 2:
				y -= SPRITE_HEIGHT;
				break;
			case 3:
				x -= SPRITE_WIDTH;
				break;
			case 4:
				x += SPRITE_WIDTH;
				break;
			default:
				break;
		}
		
		//delete the last body if didnt eat food
		Vec2 phone_p = iPhone->getPosition();
		Vec2 apple_p = apple->getPosition();
		Vec2 mac_p = mac->getPosition();
		if (x == apple_p.x && y == apple_p.y || x == phone_p.x && y == phone_p.y)
		{ 
			if (x == apple_p.x && y == apple_p.y)
			{
				isAppleEaten = true;
			}
			else
			{
				isIPhoneEaten = true;
			}
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(
				"gotItem.mp3");

			randomFood();
			score++;

			updateScore();
		}
		else if (x == mac_p.x && y == mac_p.y)
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(
				"gotItem.mp3");

			score += 5;
			randomFood();
			updateScore();
			if (snake.size() > 5)
			{
				this->removeChild(snake.at(snake.size() - 1));
				snake.pop_back();
			}
			this->removeChild(snake.at(snake.size() - 1));
			snake.pop_back(); this->removeChild(snake.at(snake.size() - 1));
			snake.pop_back();

			isMacEaten = true;
		}
		else
		{
			this->removeChild(snake.at(snake.size() - 1));
			snake.pop_back();

			if (x < 0 || x > Director::getInstance()->getVisibleSize().width ||
				y < 0 || y > Director::getInstance()->getVisibleSize().height)
			{
				newGame();
				return;
			}
			else if (isHitSnake(x, y))
			{
				newGame();
				return;
			}
			
		}

		//add a new body in front
		auto mySprite = Sprite::create("snakes.png", Rect(SPRITE_WIDTH * 3, 0,
			SPRITE_WIDTH, SPRITE_HEIGHT));
		mySprite->setAnchorPoint(Vec2(0, 0));
		mySprite->setPosition(Vec2(x, y));
		this->addChild(mySprite);

		snake.insert(snake.begin(), mySprite);
		speed_counter = 0;

		updateSprites();
		
	}
	else
	{
		speed_counter++;
	}	
}
Пример #10
0
void Game::init() {
    this->window.clearColor(glm::vec3(0.2f, 0.2f, 0.2f));

    FragmentShader f("res/texture.frag");
    VertexShader v("res/texture.vert");
    FragmentShader ffrag("res/text.frag");
    VertexShader fvert("res/text.vert");

    this->p = ShaderProgram(f, v);
    this->text = ShaderProgram(ffrag, fvert);

    this->t = Texture("res/tile.png");
    this->p["tex"] = this->t;
    this->p["P"] = glm::ortho(0.0f, (float)this->window.width, (float)this->window.height, 0.0f, -0.1f, 100.0f);
    this->p["V"] = glm::mat4(1.0f);
    this->p["M"] = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(this->window.width / 2 - (gridWidth * 25) / 2, this->window.height / 2 - (gridHeight * 25) / 2, 0.0f)), glm::vec3(25.0f, 25.0f, 0.0f));


    this->font = Texture("res/font.png", GL_NEAREST);
    this->text["tex"] = this->font;
    this->text["P"] = glm::ortho(0.0f, (float)this->window.width, (float)this->window.height, 0.0f, -0.1f, 100.0f);
    this->text["V"] = glm::mat4(1.0f);
    this->text["M"] = glm::mat4(1.0f);

    std::vector<glm::vec3> verts;
    verts.push_back(glm::vec3(0.0f, 0.0f, 0.0f));
    verts.push_back(glm::vec3(0.0f, 1.0f, 0.0f));
    verts.push_back(glm::vec3(1.0f, 1.0f, 0.0f));
    verts.push_back(glm::vec3(1.0f, 0.0f, 0.0f));
    vertices = Buffer(verts);
    vao.setAttrib(this->p, "vertexPosition", vertices, 3, GL_FLOAT, false);

    std::vector<glm::vec2> temp_uvs;
    temp_uvs.push_back(glm::vec2(0, 1));
    temp_uvs.push_back(glm::vec2(0, 0));
    temp_uvs.push_back(glm::vec2(1, 0));
    temp_uvs.push_back(glm::vec2(1, 1));
    uvs = Buffer(temp_uvs);
    vao.setAttrib(this->p, "vertexUV", uvs, 2, GL_FLOAT, false);

    std::vector<unsigned> indices;
    indices.push_back(0);
    indices.push_back(1);
    indices.push_back(2);
    indices.push_back(2);
    indices.push_back(3);
    indices.push_back(0);

    inds = Buffer(indices, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW);

    std::vector<glm::vec2> poss;
    for(int y = 0; y < gridHeight; ++y)
        for(int x = 0; x < gridWidth; ++x)
            poss.push_back(glm::vec2((float)x, (float)y));

    for(int y = 0; y < 4; ++y)
        for(int x = 0; x < 4; ++x)
            poss.push_back(glm::vec2(-6.0f + (float)x, (float)y));

    for(int y = 0; y < 4; ++y)
        for(int x = 0; x < 4; ++x)
            poss.push_back(glm::vec2(gridWidth + 1 + (float)x, (float)y));

    positions = Buffer(poss);
    vao.setAttrib(this->p, "tilePosition", positions, 2, GL_FLOAT, false, 1);
    this->vao.unbind();

    newGame();
}
Пример #11
0
GameBoard::GameBoard( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
	     cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
	     angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
	     cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
	     force, SLOT(setValue(int)) );

    connect( cannonField, SIGNAL(hit()),
	     this, SLOT(hit()) );
    connect( cannonField, SIGNAL(missed()),
	     this, SLOT(missed()) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), SLOT(fire()) );
    connect( cannonField, SIGNAL(canShoot(bool)),
	     shoot, SLOT(setEnabled(bool)) );

    QPushButton *restart 
	= new QPushButton( "&New Game", this, "newgame" );
    restart->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( restart, SIGNAL(clicked()), this, SLOT(newGame()) );

    hits = new QLCDNumber( 2, this, "hits" );
    shotsLeft = new QLCDNumber( 2, this, "shotsleft" );
    QLabel *hitsL = new QLabel( "HITS", this, "hitsLabel" );
    QLabel *shotsLeftL 
	= new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addWidget( hits );
    topBox->addWidget( hitsL );
    topBox->addWidget( shotsLeft );
    topBox->addWidget( shotsLeftL );
    topBox->addStretch( 1 );
    topBox->addWidget( restart );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();

    newGame();
}
Пример #12
0
void Game::update() {
    running = running && this->window.getKey(GLFW_KEY_ESCAPE) == GLFW_RELEASE;

    tick--;
    if(tick == 0 || (this->window.getKey(GLFW_KEY_DOWN) != GLFW_RELEASE && !prevDown)) {
        tick = ticks;

        bool canmove = true;

        const int *p = this->piece.getArray();

        posy++;

        for(int y = 0; y < 4 && canmove; ++y)
            for(int x = 0; x < 4 && canmove; ++x) {
                if(p[y * 4 + x] != 0 && posy + y >= 0)
                    canmove = canmove && (posy + y < gridHeight) && (this->grid[(posy + y) * gridWidth + posx + x] == 0);
            }

        if(canmove)
            passGridBuffer();
        else {
            posy--;
            if(!moved) {
                for(int y = 3; y >= 0; --y) {
                    for(int x = 0; x < 4; ++x) {
                        if(p[y * 4 + x] != 0 && posy + y < 0) {
                            losses++;
                            newGame();
                            prevLeft = this->window.getKey(GLFW_KEY_LEFT) != GLFW_RELEASE;
                            prevRight = this->window.getKey(GLFW_KEY_RIGHT) != GLFW_RELEASE;
                            prevUp = this->window.getKey(GLFW_KEY_UP) != GLFW_RELEASE;
                            prevZ = this->window.getKey(GLFW_KEY_SEMICOLON) != GLFW_RELEASE;
                            prevDown = this->window.getKey(GLFW_KEY_DOWN) != GLFW_RELEASE;
                            prevSpace = this->window.getKey(GLFW_KEY_SPACE) != GLFW_RELEASE;
                            prevShift = this->window.getKey(GLFW_KEY_LEFT_SHIFT) != GLFW_RELEASE;
                            return;
                        }
                        if(p[y * 4 + x] != 0)
                            this->grid[(posy + y) * gridWidth + posx + x] = p[y * 4 + x];
                    }
                }
                for(int y = posy + 3; y >= 1; --y) {
                    bool line = true;
                    for(int x = 0; x < gridWidth && line; ++x)
                        line = line && (this->grid[y * gridWidth + x] != 0);
                    if(line) {
                        for(int ly = y - 1; ly >= 0; --ly)
                            for(int x = 0; x < gridWidth; ++x)
                                this->grid[(ly + 1) * gridWidth + x] = this->grid[ly * gridWidth + x];
                        score++;
                        ticks-=2;
                        if(ticks < 1)
                            ticks = 1;
                        y++;
                    }
                }
                held = false;
                choosePiece();
            }
            moved = false;
        }
    }
    if(this->window.getKey(GLFW_KEY_SPACE) != GLFW_RELEASE && !prevSpace) {
        bool canmove = true;

        const int *p = this->piece.getArray();

        while(canmove) {

            posy++;

            for(int y = 3; y >= 0 && canmove; --y)
                for(int x = 0; x < 4 && canmove; ++x) {
                    if(p[y * 4 + x] != 0 && posy + y >= 0)
                        canmove = canmove && (posy + y < gridHeight) && (this->grid[(posy + y) * gridWidth + posx + x] == 0);
                }
        }

        posy--;
        for(int y = 0; y < 4; ++y) {
            for(int x = 0; x < 4; ++x) {
                if(p[y * 4 + x] != 0 && posy + y < 0) {
                    losses++;
                    newGame();
                    prevLeft = this->window.getKey(GLFW_KEY_LEFT) != GLFW_RELEASE;
                    prevRight = this->window.getKey(GLFW_KEY_RIGHT) != GLFW_RELEASE;
                    prevUp = this->window.getKey(GLFW_KEY_UP) != GLFW_RELEASE;
                    prevZ = this->window.getKey(GLFW_KEY_SEMICOLON) != GLFW_RELEASE;
                    prevDown = this->window.getKey(GLFW_KEY_DOWN) != GLFW_RELEASE;
                    prevSpace = this->window.getKey(GLFW_KEY_SPACE) != GLFW_RELEASE;
                    prevShift = this->window.getKey(GLFW_KEY_LEFT_SHIFT) != GLFW_RELEASE;
                    return;
                }
                if(p[y * 4 + x] != 0)
                    this->grid[(posy + y) * gridWidth + posx + x] = p[y * 4 + x];
            }
        }
        for(int y = posy + 3; y >= 1; --y) {
            bool line = true;
            for(int x = 0; x < gridWidth && line; ++x)
                line = line && (this->grid[y * gridWidth + x] != 0);
            if(line) {
                for(int ly = y - 1; ly >= 0; --ly) {
                    for(int x = 0; x < gridWidth; ++x)
                        this->grid[(ly + 1) * gridWidth + x] = this->grid[ly * gridWidth + x];
                }
                y++;
                ticks-=2;
                if(ticks < 1)
                    ticks = 1;
                score++;
            }
        }
        held = false;
        choosePiece();
    }

    if(this->window.getKey(GLFW_KEY_LEFT) != GLFW_RELEASE && !prevLeft) {
        bool canmove = true;

        const int *p = this->piece.getArray();

        posx--;

        for(int y = 0; y < 4 && canmove; ++y)
            for(int x = 0; x < 4 && canmove; ++x) {
                if(p[y * 4 + x] != 0 && posy + y >= 0)
                    canmove = canmove && (posx + x >= 0) && (posy + y < 0 || this->grid[(posy + y) * gridWidth + posx + x] == 0);
            }

        moved = canmove;

        if(canmove)
            passGridBuffer();
        else
            posx++;
    }
    else if(this->window.getKey(GLFW_KEY_RIGHT) != GLFW_RELEASE && !prevRight) {
        bool canmove = true;

        const int *p = this->piece.getArray();

        posx++;

        for(int y = 0; y < 4 && canmove; ++y)
            for(int x = 0; x < 4 && canmove; ++x) {
                if(p[y * 4 + x] != 0)
                    canmove = canmove && (posx + x < gridWidth) && (posy + y < 0 || this->grid[(posy + y) * gridWidth + posx + x] == 0);
            }

        moved = canmove;

        if(canmove)
            passGridBuffer();
        else
            posx--;
    }
    else if(this->window.getKey(GLFW_KEY_UP) != GLFW_RELEASE && !prevUp) {
        Mino newMino(this->piece);

        newMino.rotClock();

        const int *p = newMino.getArray();

        bool canrotate = true;

        for(int y = 0; y < 4 && canrotate; ++y)
            for(int x = 0; x < 4 && canrotate; ++x) {
                if(p[y * 4 + x] != 0)
                    canrotate = canrotate && (posx + x < gridWidth) && (posx + x >= 0) && (posy + y < 0 || this->grid[(posy + y) * gridWidth + posx + x] == 0);
            }

        moved = canrotate;

        if(canrotate) {
            this->piece = newMino;
            passGridBuffer();
        }
    }
    else if(this->window.getKey(GLFW_KEY_SEMICOLON) != GLFW_RELEASE && !prevZ) {
        Mino newMino(this->piece);

        newMino.rotCounterClock();

        const int *p = newMino.getArray();

        bool canrotate = true;

        for(int y = 0; y < 4 && canrotate; ++y)
            for(int x = 0; x < 4 && canrotate; ++x) {
                if(p[y * 4 + x] != 0)
                    canrotate = canrotate && (posx + x < gridWidth) && (posx + x >= 0) && (this->grid[(posy + y) * gridWidth + posx + x] == 0);
            }

        moved = canrotate;

        if(canrotate) {
            this->piece = newMino;
            passGridBuffer();
        }
    }

    if(this->window.getKey(GLFW_KEY_LEFT_SHIFT) != GLFW_RELEASE && !prevShift && !held) {
        held = true;

        Mino newMino(this->piece);
        this->piece = this->hold;
        this->hold = newMino;

        this->posx = 3;
        this->posy = this->piece.startOffset();

        passGridBuffer();
    }

    prevLeft = this->window.getKey(GLFW_KEY_LEFT) != GLFW_RELEASE;
    prevRight = this->window.getKey(GLFW_KEY_RIGHT) != GLFW_RELEASE;
    prevUp = this->window.getKey(GLFW_KEY_UP) != GLFW_RELEASE;
    prevZ = this->window.getKey(GLFW_KEY_SEMICOLON) != GLFW_RELEASE;
    prevDown = this->window.getKey(GLFW_KEY_DOWN) != GLFW_RELEASE;
    prevSpace = this->window.getKey(GLFW_KEY_SPACE) != GLFW_RELEASE;
    prevShift = this->window.getKey(GLFW_KEY_LEFT_SHIFT) != GLFW_RELEASE;
}
Пример #13
0
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags wf) 
  : QMainWindow(parent, wf)
{
  //setMinimumSize(geometry().size());
  //setMaximumSize(geometry().size());

  contrdirs[Cell::U] = Cell::D;
  contrdirs[Cell::R] = Cell::L;
  contrdirs[Cell::D] = Cell::U;
  contrdirs[Cell::L] = Cell::R;

#ifndef QTOPIA_PHONE
  QString appdir = qApp->applicationDirPath();
  soundpath = appdir + "/sounds/";
  if(!QFile::exists(soundpath))
    soundpath = appdir + "/../share/qnetwalk/sounds/";
  winsound   = new QSound(soundpath + "win.wav");
  turnsound   = new QSound(soundpath + "turn.wav");
  clicksound   = new QSound(soundpath + "click.wav");
  startsound   = new QSound(soundpath + "start.wav");
  connectsound = new QSound(soundpath + "connect.wav");
#else
  QString appdir = qApp->applicationDirPath();
  soundpath = ":sound/qnetwalk/";

  winsound   = new QSound(soundpath + "win");
  turnsound   = new QSound(soundpath + "turn");
  clicksound   = new QSound(soundpath + "click");
  startsound   = new QSound(soundpath + "start");
  connectsound = new QSound(soundpath + "connect");
#endif

  QSettings settings("QNetEor", "QNetEor");
  settings.beginGroup("QNetEor");
  username = settings.value("Username", getenv("USER")).toString();
  bool issound = settings.value("Sound", true).toBool();

  highscores = settings.value("Highscores").toStringList();
  if(highscores.count() != NumHighscores * 8)
  {
    highscores.clear();
    for(int i = 1; i < 5; i++)
    {
      for(int scores = 20 * i; scores < 30 * i; scores += i)
      {
        highscores.append("...");
        highscores.append(QString::number(scores));
      }
    }
  }

  skill = settings.value("Skill", Novice).toInt();
  if(skill != Novice && skill != Normal && skill != Expert)
    skill = Master;
  settings.endGroup();

  for(int i = 1; i < qApp->argc(); i++)
  {
    QString argument = qApp->argv()[i];
    if(argument == "-novice")
      skill = Novice;
    else if(argument == "-amateur")
      skill = Normal;
    else if(argument == "-expert")
      skill = Expert;
    else if(argument == "-master")
      skill = Master;
    else if(argument == "-nosound")
      issound = false;
  }

  setWindowTitle(tr("QNeoroid"));
  setWindowIcon(QPixmap(":/computer2.png"));

#ifdef QTOPIA_PHONE
  QMenu *m = QSoftMenuBar::menuFor(this);
#else
  QMenu *m = menuBar()->addMenu(tr("Options"));
#endif  
  soundaction = new QAction(tr("&Sound"), this);
  soundaction->setCheckable(true);
  soundaction->setChecked(issound);

  gamemenu = m->addMenu(tr("&Game"));
  gamemenu->addAction(QPixmap(":/newgame.png"), tr("&New"), this, SLOT(newGame()));
  gamemenu->addAction(QPixmap(":/highscores.png"), tr("&Highscores"), this, SLOT(showHighscores()));
  gamemenu->addAction(soundaction);
#ifndef QTOPIA_PHONE
  gamemenu->addSeparator();
  gamemenu->addAction(QPixmap(":/quit.png"), tr("&Quit"), qApp, SLOT(closeAllWindows()));
#endif

  skillmenu = m->addMenu(tr("&Skill"));
  skillActionGroup = new QActionGroup(this);
  QAction* action;
  action = skillActionGroup->addAction(tr("&Novice"));
  action->setCheckable(true);
  if(skill == Novice)
    action->setChecked(true);
  connect(action, SIGNAL(triggered()), this, SLOT(setSkillNovice()));
  action = skillActionGroup->addAction(tr("&Amateur"));
  action->setCheckable(true);
  if(skill == Normal)
    action->setChecked(true);
  connect(action, SIGNAL(triggered()), this, SLOT(setSkillNormal()));
  action = skillActionGroup->addAction(tr("&Expert"));
  action->setCheckable(true);
  if(skill == Expert)
    action->setChecked(true);
  connect(action, SIGNAL(triggered()), this, SLOT(setSkillExpert()));
  action = skillActionGroup->addAction(tr("&Master"));
  action->setCheckable(true);
  if(skill == Master)
    action->setChecked(true);
  connect(action, SIGNAL(triggered()), this, SLOT(setSkillMaster()));
  skillmenu->addActions(skillActionGroup->actions());

  QMenu* helpmenu = m->addMenu(tr("&Help"));
  helpmenu->addAction(tr("&Rules of Play"), this, SLOT(help()));
  helpmenu->addAction(QPixmap(":/homepage.png"), tr("&Homepage"), this, SLOT(openHomepage()));
  helpmenu->addSeparator();
  helpmenu->addAction(QPixmap(":/qnetwalk.png"), tr("&About QNeoroid"), this, SLOT(about()));
  helpmenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));

  QToolBar* toolbar = new QToolBar(this);
  toolbar->setFloatable(false);
  toolbar->setMovable(false);
  toolbar->addAction(QPixmap(":/newgame.png"), tr("New Game"), this, SLOT(newGame()));
  toolbar->addAction(QPixmap(":/highscores.png"), tr("Show Highscores"), this, SLOT(showHighscores()));
  //toolbar->addWidget(new QLabel(tr("Moves"),this));
  lcd = new QLCDNumber(toolbar);
  lcd->setFrameStyle(QFrame::Plain);
  toolbar->addWidget(lcd);
  //toolbar->addWidget(new QLabel(tr("Left:"),this));
  cellsLcd = new QLCDNumber(toolbar);
  cellsLcd->setFrameStyle(QFrame::Plain);
  toolbar->addWidget(cellsLcd);
  addToolBar(toolbar);

  Cell::initPixmaps();
  srand(time(0));
  setSkill(skill);
  installEventFilter(this);
  resize(240,320);
}
Пример #14
0
/**
 * Function:  unittest4
 * Inputs:  printVal, seed, results
 * Outputs: none
 * Description: tests getWinners() function in dominion.c
 */
void unitTest4(int printVal, int seed, struct results *result){

	int i, r=0;
	int players[MAX_PLAYERS] = {0};

	struct playerGroup *playGroup = newPlayerGroup();

	// setup the kingdom cards available
	int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
					 sea_hag, tribute, smithy};

	// setup the struct for the control and active Games
	struct gameState *controlGame = newGame();
	struct gameState *activeGame = newGame();

	playGroup->numPlayers = random_number(2, MAX_PLAYERS);
	initializeGame(playGroup->numPlayers, k, seed, controlGame);

	playGroup->playerValues[0]->cardCounts[0] = 23;
	playGroup->playerValues[1]->cardCounts[0] = 46;
	playGroup->playerValues[2]->cardCounts[0] = 75;
	playGroup->playerValues[3]->cardCounts[0] = 66;

	for(i = 0; i < playGroup->numPlayers; i++)
	{
		updateCards(i, playGroup->playerValues[i], controlGame);
	}

	//copy the values from the activeGame into the controlGame
	memcpy(activeGame, controlGame, sizeof(struct gameState));

	// calculate the scores for the players
	for(i = 0; i < MAX_PLAYERS; i++)
	{
		playGroup->playerValues[i]->score = calculate_total(i, controlGame);
	}

	// run the getWinners function
	r = getWinners(players, activeGame);
	assert(r == 0);

	int winningScore = playGroup->playerValues[0]->score;
	int curWinner = 0;
	playGroup->playerValues[0]->winner = 1;

	for(i = 0; i < MAX_PLAYERS; i++)
	{

		if(playGroup->playerValues[i]->score >= winningScore)
		{
			winningScore = playGroup->playerValues[i]->score;
			playGroup->playerValues[curWinner]->winner = 0;
			playGroup->playerValues[i]->winner = 1;
			curWinner = i;
		}

	}

	for(i=0; i < MAX_PLAYERS; i++)
	{
		int j;
		int score = scoreFor(i, activeGame);

		if(!(playGroup->playerValues[i]->winner == players[i]) || !(score == playGroup->playerValues[i]->score))
		{
			printf("TEST: %d, FAIL: Player: %d of %d players\nScore: %d, Expected: %d, Winner Val Returned: %d,"
					" Expected: %d\n",
					result->testNum, i, playGroup->numPlayers, score,
					playGroup->playerValues[i]->score, players[i], playGroup->playerValues[i]->winner);
			result->testsFailed++;
		}
		else
		{
			assert(playGroup->playerValues[i]->winner == players[i]);

			if(PRINTPASS){
				printf("TEST: %d, PASS: Player: %d of %d players\nScore: %d, Expected: %d, Winner Val Returned: %d,"
						" Expected: %d\n",
						result->testNum, i, playGroup->numPlayers, score,
						playGroup->playerValues[i]->score, players[i], playGroup->playerValues[i]->winner);
			}
		}

		if(!(scoreFor(i, activeGame) == playGroup->playerValues[i]->score))
		{
			printf("HAND: ");
			for(j = 0; j < activeGame->handCount[i]; j++)
			{
				printf("%d,", activeGame->hand[i][j]);
			}
			printf("\n");
			printf("DECK: ");
			for(j = 0; j < activeGame->deckCount[i]; j++)
			{
				printf("%d,", activeGame->deck[i][j]);
			}
			printf("\n");
			printf("DISCARD: ");
			for(j = 0; j < activeGame->discardCount[i]; j++)
			{
				printf("%d,", activeGame->discard[i][j]);
			}
			printf("\n");
			printf("CURSE: %d, ESTATES: %d, DUCHY: %d, PROVINCE: %d, GREAT_HALL:%d, GARDENS: %d, totalCards: %d\n",
					playGroup->playerValues[i]->cardCounts[CURSE_CT], playGroup->playerValues[i]->cardCounts[ESTATE_CT],
					playGroup->playerValues[i]->cardCounts[DUCHY_CT], playGroup->playerValues[i]->cardCounts[PROVINCE_CT],
					playGroup->playerValues[i]->cardCounts[GREATHALL_CT], playGroup->playerValues[i]->cardCounts[GARDENS_CT],
					playGroup->playerValues[i]->totalCards);
		}
	}


	result->testsPassed++;

	// clean up memory
	for(i = 0; i < MAX_PLAYERS; i++){
		free(playGroup->playerValues[i]);
	}
	free(playGroup);
	free(controlGame);
	free(activeGame);
}
Пример #15
0
void toMenu()
{
    
    
    BITMAP *menuBuffer = NULL;
    menuBuffer = create_bitmap(1024,768); //Create an empty bitmap.
    BITMAP *menuBackground = NULL;
    menuBackground = load_bitmap("Menu Background.bmp", NULL); // Load our picture
    BITMAP *highlighter = NULL; 
    highlighter = load_bitmap("Menu Highlighter.bmp", NULL); // Load our picture
    BITMAP *smoke = NULL; 
    smoke = load_bitmap("Menu Smoke.bmp", NULL); // Load our picture

    MIDI *menuMusic = NULL;
    menuMusic = load_midi("Soundtrack1.mid");

    
    SAMPLE *menuClick = load_sample("Click.wav");

 
    clear_bitmap(menuBuffer); // Clear the contents of the buffer bitmap
    
    int highlightedOption = 1;
    int inMenu = 1;
    int smokePosition = 1024;
    int smokePosition2 = 1024;

    
    draw_sprite(menuBuffer, menuBackground, 0, 0);
    draw_sprite(menuBuffer, highlighter, 6, 186);
    blit(menuBuffer, screen, 0,0,0,0,1024,768);//Draw the buffer to the screen
    play_midi(menuMusic, 1);
    while (inMenu == 1)
    {
        draw_sprite(menuBuffer, menuBackground, 0, 0);
        
        smokePosition --;
        smokePosition2 -= 3;
        if (smokePosition <= -1024)
        {
           smokePosition = 0;
        }   

         
        readkey();
        
        if(key[KEY_UP]) 
        {
            play_sample(menuClick, 155, 0, 2000, 0);
            highlightedOption--;
            if (highlightedOption <= 0)
            {
               highlightedOption = 5;
            }
           
        }
        else if(key[KEY_DOWN])
        {
           play_sample(menuClick, 155, 0, 2000, 0);
           highlightedOption++;
            if (highlightedOption >= 6)
            {
               highlightedOption = 1;
            }  
        }   
        else if(key[KEY_ENTER])
        {
            play_sample(menuClick, 155, 0, 4000, 0);
            switch (highlightedOption)
            {
            case 1:
                isXenoPatriots = selectRace();
                newGame();
                startGame();
                play_midi(menuMusic, 1);
                break;
            case 2:
                loadGame();
                break;
            case 3:
                gameOptions();
                break;
            case 4:
                
                break;
            case 5:
                quitGame();
                inMenu ^= 0;
                return;
                
                break;
            }
         }

       
    
        switch (highlightedOption)
        {
            case 1:
                draw_sprite(menuBuffer, highlighter, 6, 186);
                break;
            case 2:
                draw_sprite(menuBuffer, highlighter, 6, 278);
                break;
            case 3:
                draw_sprite(menuBuffer, highlighter, 6, 373);
                break;
            case 4:
                draw_sprite(menuBuffer, highlighter, 6, 465);
                break;
            case 5:
                draw_sprite(menuBuffer, highlighter, 6, 629);
                break;
         }
         /*draw_sprite(menuBuffer, smoke, smokePosition, 0);
         draw_sprite(menuBuffer, smoke, smokePosition + 1024, 0);
         draw_sprite(menuBuffer, smoke, smokePosition2, 0);
         draw_sprite(menuBuffer, smoke, smokePosition2 + 1024, 0);*/
         blit(menuBuffer, screen, 0,0,0,0,1024,768);//Draw the buffer to the screen
         
     }  


}
Пример #16
0
int main (int argc, char* argv[]) 
{
	int numberOfPlayer = 2; 
	int randomSeed, handCounts, deckCounts, discardCounts, cardPositions;
	int i, j;
	int player;
	int card;
	time_t t;
	
	if (argc == 2) 
	{
		printf ("TAKE INPUT SEED\n");
		randomSeed = atoi(argv[1]);
	}
	else 
	{
		printf ("TAKE RANDOMIZED SEED\n");
		randomSeed = rand()%20 + 1;
	}
	
	int kingdomCards[10] = {smithy,adventurer,gardens,embargo,cutpurse,mine,ambassador,
	       outpost,baron,tribute};
	cardPositions = 0;
	srand((unsigned) time(&t));
	struct gameState *game;
	for (i = 0; i < MAX_TEST; i++) 
	{	
		game = newGame();
		
		// Initialize the game
		initializeGame(numberOfPlayer, kingdomCards, randomSeed, game);
		player = game->whoseTurn;
		handCounts = rand()%20 + 2;
		game->handCount[player] = handCounts;
		
		// Put the Council Room Card to hand 
		game->hand[player][cardPositions] = council_room;
		for (j = 1; j < handCounts; j++) 
		{
			card = rand() % 27;
			game->hand[player][j] = card;
		}
		deckCounts = rand() % 30 + 5;
		printf ("DECK COUNTS: %d\n",deckCounts);
		game->deckCount[player] = deckCounts;
		for (j = 0; j < deckCounts; j++) 
		{
			card = rand() % 27;
			game->deck[player][j] = card;
		}
		discardCounts = rand() % 10;
		game->discardCount[player] = discardCounts;
		for (j = 0; j < discardCounts; j++) 
		{
			card = rand() % 27;
			game->discard[player][j] = card;
		}
		
		// Use the Council Room Card 
		cardEffect(council_room, 0, 0, 0, game, cardPositions, 0);
		
		// Check if we got the right hand counts 
		if (game->handCount[player] == (handCounts + 4))
		{
			printf("TEST SUCCESSFUL: GET THE RIGHT HAND COUNTS\n");
		}
		else
		{
			printf("TEST FAILED: GET THE WRONG HAND COUNTS\n");
		}
		
		// Check if we got the right deck counts 
		if (game->deckCount[player] == (deckCounts - 6))
		{
			printf("TEST SUCCESSFUL: GET THE RIGHT DECK COUNTS\n");
		}
		else
		{
			printf("TEST FAILED: GET THE WRONG DECK COUNTS\n");
		}
		
		// Check if we got the right discard counts 
		if (game->discardCount[player] == (discardCounts + 1))
		{
			printf("TEST SUCCESSFUL: GET THE RIGHT DISCARD COUNTS\n");
		}
		else
		{
			printf("TEST FAILED: GET THE WRONG DISCARD COUNTS\n");
		}
		
		// Free the memory 
		free(game);
	}
	return 0;
}
Пример #17
0
//-----------------------------------------------------------------------------
// 総当たり
//-----------------------------------------------------------------------------
int SoAtari(HWND hwnd) {
	SuDokuGame save = g_game;

	int loop = 1;
	TCHAR buf[512];
	std::queue<SuDokuGame> games;

	games.push(g_game);

	while (!games.empty()) {
		SuDokuGame curGame = games.front();
		games.pop();

		// 候補が二個のものを探して、そこから新しいゲームを作る
		for (int y = 0; y < 9; y++) {
			for (int x = 0; x < 9; x++) {
				int cnt = curGame.GetCandidateCount(y, x, NULL);
				if (cnt == 2) {
					int n;
					for (n = 0; n < 9; n++) {
						if (curGame.get_Candidate(y, x, n) == 1) {
							SuDokuGame newGame(curGame);
							newGame.FixCell(y, x, n + 1);
							newGame.ReparseAll();
							if (!newGame.IsFinished()) {
								//OutputDebugString(_T("手詰まり\n"));
							} else {
								OutputDebugString(_T("解けた!!\n"));
								g_game = newGame;
								return 1;
							}
							if (newGame.IsGameover() == false) {
								wsprintf(buf, _T("%2d: (%d,%d) = %d のパターンを登録\n"), loop, y, x, n + 1);
								OutputDebugString(buf);
								games.push(newGame);
							} else {
								// 選択した結果、ゲームオーバーにつながる場合は、次の選択肢が無条件に有効なパターンのはず。
								OutputDebugString(_T("ゲームオーバー!!\n"));
							}
							n++;
							break;
						}
					}
					for (; n< 9; n++) {
						if (g_game.get_Candidate(y, x, n) == 1) {
							SuDokuGame newGame(g_game);
							newGame.FixCell(y, x, n + 1);
							newGame.ReparseAll();
							if (!newGame.IsFinished()) {
								//OutputDebugString(_T("手詰まり\n"));
							} else {
								OutputDebugString(_T("解けた!!\n"));
								g_game = newGame;
								return 1;
							}
							if (newGame.IsGameover() == false) {
								wsprintf(buf, _T("%2d: (%d,%d) = %d のパターンを登録\n"), loop, y, x, n + 1);
								OutputDebugString(buf);
								games.push(newGame);
							}
							n++;
							wsprintf(buf, _T("---残り %4d -----------------------------------------------------\n"), games.size());
							OutputDebugString(buf);
							loop++;
							goto skip;
						}
					}
				}
			}
		}
skip:
		;
	}

	return 0;
}
Пример #18
0
int main() {

	srand(time(NULL));
	int gameSeed = rand() % 1000 + 1;
	int p = 0; //player 1
	int numPlayer = 4;
	int k[10] = {adventurer, council_room, feast, gardens, mine,
				 remodel, smithy, village, baron, great_hall};

	struct gameState* GS = newGame();

	initializeGame(numPlayer, k, gameSeed, GS);

	GS->hand[p][4] = smithy; //5th card in hand is smithy

	printf("Playing Smithy card and testing...\n");

	/*Checking handcount and cards in hand before playing smithy*/
	printf("Hand count before Smithy is %d...\n", GS->handCount[p]);
	int i = 0, cardStatus;
	char c[25];
	for(i = 0; i < GS->handCount[p]; i++){
		cardNumToName(GS->hand[p][i], c);	//Converts card number to string
		printf( "%s, ", c);
		if(strcmp(c, "Smithy") == 0){
			cardStatus = 1;	//Card is present in hand
		}
	}

	/*Check if smithy card is in hand before use*/
	if(cardStatus == 1){
		printf("\nTest PASSED, card is present in player %d's hand\n\n", p);
	} else {
		printf("\nTest FAILED, card is NOT present in player %d's hand\n\n", p);
	}

	smithyCard(p, GS, 4);	//Play smithy card

	cardStatus = 0; //Reset to zero

	/*Checking handcount and cards in hand after playing smithy*/
	printf("Hand count after Smithy is %d...\n", GS->handCount[p]);
	for(i = 0; i < GS->handCount[p]; i++){
		cardNumToName(GS->hand[p][i], c);	//Converts card number to string
		printf( "%s, ", c);
		if(strcmp(c, "Smithy") == 0){
			cardStatus = 1;	//Card is present in hand
		}
	}

	/*Check if smithy card is in hand*/
	if(cardStatus == 0){
		printf("\nTest PASSED, card is NOT present in player %d's hand\n\n", p);
	} else {
		printf("\nTest FAILED, card is present in player %d's hand\n\n", p);
	}

	printf("Testing for correct number of cards drawn...\n");
	/*Check current state player's handcount +3 cards after discard is 5 cards*/
	if(GS->handCount[p] == 7){
		printf("Test PASSED, Player %d drew +3 cards\n\n", p);
	} else {
		printf("Test FAILED, Player %d drew incorrect amount of cards\n\n", p);
	}

	printf("Checking if Smithy Card is in played pile...\n");
	/*Check if card is in played pile*/
	if(GS->playedCards[p] == smithy){
		printf("Test PASSED, Smithy is in played pile\n\n");
	} else {
		printf("Test FAILED, Smithy is NOT in played pile\n\n");
	}

/*Check if smithy card has been discarded from hand after card effects*/
	for(i = 0; i < GS->handCount[p]; i++){
		cardNumToName(GS->hand[p][i], c);	//Converts card number to string
		printf( "%s, ", c);
		if(strcmp(c, "Smithy") != 0){
			cardStatus = 0;	//Card is NOT present in hand
		}
	}

	printf("\nTesting if card is discarded from hand...\n");
	if(cardStatus == 0){
		printf("Test PASSED, Smithy is discarded from player %d's hand after use\n\n", p);
	} else {
		printf("Test FAILED, Smithy card is NOT discarded from player %d's hand after use\n\n", p);
	}

	return 0;

}
Пример #19
0
GameBoard::GameBoard( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    setMinimumSize( 500, 355 );

    quit = new QPushButton( "Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    frame = new QFrame( this, "cannonFrame" );
    frame->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );

    cannonField = new CannonField( this, "cannonField" );
    cannonField->setBackgroundColor( QColor( 250, 250, 200) );

    connect( angle,SIGNAL(valueChanged(int)), cannonField,SLOT(setAngle(int)));
    connect( cannonField,SIGNAL(angleChanged(int)), angle,SLOT(setValue(int)));

    connect( force,SIGNAL(valueChanged(int)), cannonField,SLOT(setForce(int)));
    connect( cannonField,SIGNAL(forceChanged(int)), force,SLOT(setValue(int)));

    connect( cannonField, SIGNAL(hit()),SLOT(hit()) );
    connect( cannonField, SIGNAL(missed()),SLOT(missed()) );

    angle->setValue( 60 );
    force->setValue( 25 );

    shoot = new QPushButton( "Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), SLOT(fire()) );

    restart = new QPushButton( "New Game", this, "newgame" );
    restart->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( restart, SIGNAL(clicked()), SLOT(newGame()) );

    hits  	       = new QLCDNumber( 2, this, "hits" );
    shotsLeft 	       = new QLCDNumber( 2, this, "shotsleft" );
    QLabel *hitsL      = new QLabel( "HITS", this, "hitsLabel" );
    QLabel *shotsLeftL = new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

    QAccel *accel = new QAccel( this );
    accel->connectItem( accel->insertItem( Key_Space), this, SLOT(fire()) );
    accel->connectItem( accel->insertItem( Key_Q), qApp, SLOT(quit()) );

    quit->setGeometry( 10, 10, 75, 30 );
    angle->setGeometry( 10, quit->y() + quit->height() + 10, 75, 130 );
    force->setGeometry( 10, angle->y() + angle->height() + 10, 75, 130 );
    frame->move( angle->x() + angle->width() + 10, angle->y() );
    cannonField->move( frame->x() + 2, frame->y() + 2 );
    shoot->setGeometry( 10, 315, 75, 30 );
    restart->setGeometry( 380, 10, 110, 30 );
    hits->setGeometry( 130, 10, 40, 30 );
    hitsL->setGeometry( hits->x() + hits->width() + 5, 10, 60, 30 );
    shotsLeft->setGeometry( 240, 10, 40, 30 );
    shotsLeftL->setGeometry( shotsLeft->x()+shotsLeft->width()+5, 10, 70, 30 );

    newGame();
}
Пример #20
0
jogo::jogo()
{
   tab = NULL;
   newGame();
    //ctor
}
Пример #21
0
void Game::levelUp()
{
	// This function is called when a player clears all bricks from the screen

	// Increase the number of lives by 1
	setLives(getLives() + 1);
	// Increase the rounds
	m_Round++;

	// If the current round is equal to or greater than the max rounds 
	if(m_Round > GAME_MAX_ROUNDS)
	{
		// Start a new game
		newGame();
	}

	// Sets the background image colour based on the current round
	switch(m_Round)
		{
		case 0:
			// Default
			m_Textures[0]->setColor(OpenGLColorRGB(1.0f, 1.0f, 1.0f));
			break;
		case 1:
			// Green
			m_Textures[0]->setColor(OpenGLColorRGB(0.5f, 1.0f, 0.5f));
			break;
		case 2:
			// Orange
			m_Textures[0]->setColor(OpenGLColorRGB(1.0f, 0.5f, 0.0f));
			break;
		case 3:
			// Purple
			m_Textures[0]->setColor(OpenGLColorRGB(0.5f, 0.5f, 0.0f));
			break;
		case 4:
			// Red
			m_Textures[0]->setColor(OpenGLColorRGB(1.0f, 0.5f, 0.5f));
			break;
		case 5:
			// Yellow
			m_Textures[0]->setColor(OpenGLColorRGB(1.0f, 1.0f, 0.0f));
			break;
		}

	// Add another row of bricks
	for(int i = 0; i < GAME_BRICKS_PER_ROW; i++)
	{
		addGameObject(new Brick());
	}


	Ball* ball = (Ball*)getGameObjectByType(GAME_BALL_TYPE);
	if(ball != NULL)
	{
		// Increases the ball's speed by 25% each time this function is called
		// Change GAME_SPEED_MOD in globals to change the speed increase per level
		float prevSpeed = ball->getSpeed();

		// Go through all game objects and reset them
		// Except for the paddle
		for(int i = 0; i < m_GameObjects.size(); i++)
		{
			if(m_GameObjects.at(i)->getType() != GAME_PADDLE_TYPE)
			{
				m_GameObjects.at(i)->reset();
			}
		}

		ball->setSpeed(prevSpeed * GAME_SPEED_MOD);
	}

	// Call the placeBrick function to space bricks
	// For a new round of play
	placeBricks();
}
Пример #22
0
Window::Window() :
	m_seed(0),
	m_difficulty(QSettings().value("Difficulty", 5).toInt()),
	m_algorithm(QSettings().value("Algorithm", 1).toInt())
{
	// Create board
	QUndoStack* moves = new QUndoStack(this);
	m_board = new Board(moves, this);
	m_seed = QSettings().value("Current/Seed").toInt();
	setCentralWidget(m_board);

	// Create menubar
	QMenu* game_menu = menuBar()->addMenu(tr("&Game"));

	QAction* new_action = game_menu->addAction(QIcon::fromTheme("document-new"), tr("&New"), this, SLOT(newGame()), QKeySequence::New);
	QAction* restart_action = game_menu->addAction(QIcon::fromTheme("view-refresh"), tr("&Restart Game"), this, SLOT(restartGame()), QKeySequence::Refresh);
	game_menu->addAction(tr("&Details"), this, SLOT(showDetails()));
	game_menu->addSeparator();
	QAction* quit_action = game_menu->addAction(QIcon::fromTheme("application-exit"), tr("Quit"), this, SLOT(close()), QKeySequence::Quit);
	quit_action->setMenuRole(QAction::QuitRole);

	QMenu* move_menu = menuBar()->addMenu(tr("&Move"));

	QAction* undo_action = move_menu->addAction(QIcon::fromTheme("edit-undo"), tr("&Undo"), moves, SLOT(undo()), QKeySequence::Undo);
	undo_action->setEnabled(false);
	connect(moves, &QUndoStack::canUndoChanged, undo_action, &QAction::setEnabled);

	QAction* redo_action = move_menu->addAction(QIcon::fromTheme("edit-redo"), tr("&Redo"), moves, SLOT(redo()), QKeySequence::Redo);
	redo_action->setEnabled(false);
	connect(moves, &QUndoStack::canRedoChanged, redo_action, &QAction::setEnabled);

	QMenu* appearance_menu = menuBar()->addMenu(tr("&Appearance"));

	QMap<QString, QString> colors;
	colors.insert(tr("Blue"), "#0055ff");
	colors.insert(tr("Charcoal"), "#3d3d3d");
	colors.insert(tr("Green"), "#00aa00");
	colors.insert(tr("Midnight"), "#00007f");
	colors.insert(tr("Plum"), "#aa007f");
	colors.insert(tr("Red"), "#ff0000");
	colors.insert(tr("Yellow"), "#ffff00");
	QString selected_color = QSettings().value("Appearance", "#0055ff").toString();

	m_colors = new QActionGroup(this);
	QMapIterator<QString, QString> i(colors);
	while (i.hasNext()) {
		i.next();
		QAction* color_action = appearance_menu->addAction(i.key());
		color_action->setData(i.value());
		color_action->setCheckable(true);
		m_colors->addAction(color_action);
		if (i.value() == selected_color) {
			color_action->setChecked(true);
		}
	}

	connect(m_colors, &QActionGroup::triggered, this, &Window::changeAppearance);

	appearance_menu->addAction(tr("Custom..."), this, SLOT(changeAppearanceCustom()));

	QMenu* settings_menu = menuBar()->addMenu(tr("&Settings"));
	settings_menu->addAction(tr("Application &Language..."), this, SLOT(setLocale()));

	QMenu* help_menu = menuBar()->addMenu(tr("&Help"));
	QAction* about_action = help_menu->addAction(tr("&About"), this, SLOT(about()));
	about_action->setMenuRole(QAction::AboutRole);
	QAction* about_qt_action = help_menu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
	about_qt_action->setMenuRole(QAction::AboutQtRole);

	// Create toolbar
	QToolBar* toolbar = new QToolBar(this);
	toolbar->setIconSize(QSize(22, 22));
	toolbar->setFloatable(false);
	toolbar->setMovable(false);
	toolbar->setToolButtonStyle(Qt::ToolButtonFollowStyle);
	toolbar->addAction(new_action);
	toolbar->addAction(restart_action);
	toolbar->addSeparator();
	toolbar->addAction(undo_action);
	toolbar->addAction(redo_action);
	addToolBar(toolbar);
	setContextMenuPolicy(Qt::NoContextMenu);

	// Restore size and position
	resize(400,400);
	restoreGeometry(QSettings().value("Geometry").toByteArray());

	// Restore current game
	loadGame();
}
Пример #23
0
void MainWindow::onMoveWasMade(const Grid *newMove)
 {
#ifdef DEBUG_VIEW
    print("mainWindow->onMoveWasMade");
#endif
    switchCurrentPlayer();
    emit validMove(newMove);
 }
void MainWindow::onMakeMove(Grid *newMove)
{
#ifdef DEBUG_VIEW
    printLine2("mainWindow->onMakeMove() with new grid at address: ", newMove);
#endif
    emit makeMove(newMove);

}
void MainWindow::init()
{
    //Window to widget
    connect(this, SIGNAL(validMove(const Grid*)), m_mainWidget, SLOT(onUpdateGrid(const Grid*)));
    connect(this, SIGNAL(tellResetBoard()), m_mainWidget, SLOT(onResetBoard()));

    //Widget to window
    connect(m_mainWidget, SIGNAL(onMakeMove(Grid*)), this, SLOT(onMakeMove(Grid *)));
    connect(m_mainWidget, SIGNAL(swapInHuman(Elements::PlayerType)), this, SLOT(onSwapInHuman(Elements::PlayerType)));
    connect(m_mainWidget, SIGNAL(swapInAI(Elements::PlayerType)), this, SLOT(onSwapInAI(Elements::PlayerType)));
    connect(m_mainWidget, SIGNAL(createAI(Elements::PlayerType,QString)), this, SLOT(onCreateAI(Elements::PlayerType,QString)));
    connect(m_mainWidget, SIGNAL(trainAI(Elements::PlayerType)), this, SLOT(onTrainAI(Elements::PlayerType)));
    connect(m_mainWidget, SIGNAL(newGame()), this, SLOT(onNewGame()));
}
Пример #24
0
KBBGame::KBBGame() : KTopLevelWidget()     
{
  int i;

  setCaption(QString("KBlackBox ")+KBVERSION);

  menu                = new KMenuBar(this, "menu");
  QPopupMenu *game    = new QPopupMenu;
  QPopupMenu *file    = new QPopupMenu;
  sizesm  = new QPopupMenu;
  ballsm  = new QPopupMenu;
  QPopupMenu *help = new QPopupMenu;
  options = new QPopupMenu;
 
  CHECK_PTR( file );
  CHECK_PTR( game );
  CHECK_PTR( help );
  CHECK_PTR( sizesm );
  CHECK_PTR( ballsm );
  CHECK_PTR( options );
  CHECK_PTR( menu );

  help->insertItem( trans->translate("&Help"), ID_HELP );
  help->setAccel( CTRL+Key_H, ID_HELP );
  help->insertSeparator();
  help->insertItem( trans->translate("&About KBlackBox"), ID_ABOUT );
  help->setAccel( CTRL+Key_A, ID_ABOUT );
  help->insertItem( trans->translate("About &Qt"), ID_ABOUT_QT );

		    
  file->insertItem( trans->translate("&Quit"), ID_QUIT );
  file->setAccel( CTRL+Key_Q, ID_QUIT );

  game->insertItem( trans->translate("&New"), ID_NEW );
  game->insertItem( trans->translate("&Give up"), ID_GIVEUP );
  game->insertItem( trans->translate("&Done"), ID_DONE );
  game->insertSeparator();
  game->insertItem( trans->translate("&Resize"), ID_RESIZE );

  sizes1id = sizesm->insertItem( "  8 x 8  ", this, SLOT(size1()) );
  sizes2id = sizesm->insertItem( " 10 x 10 ", this, SLOT(size2()) );
  sizes3id = sizesm->insertItem( " 12 x 12 ", this, SLOT(size3()) );
  sizesm->setCheckable( TRUE );

  balls1id = ballsm->insertItem( " 4 ", this, SLOT(balls1()) );
  balls2id = ballsm->insertItem( " 6 ", this, SLOT(balls2()) );
  balls3id = ballsm->insertItem( " 8 ", this, SLOT(balls3()) );
  ballsm->setCheckable( TRUE );

  options->insertItem( trans->translate("&Size"), sizesm );  
  options->insertItem( trans->translate("&Balls"), ballsm );
  tut1id = options->insertItem( trans->translate("&Tutorial"),
				this, SLOT(tutorialSwitch()) );
  options->setCheckable( TRUE );

  connect( file, SIGNAL(activated(int)), SLOT(callBack(int)) );
  connect( help, SIGNAL(activated(int)), SLOT(callBack(int)) );
  connect( game, SIGNAL(activated(int)), SLOT(callBack(int)) );
 
  menu->insertItem( trans->translate("&File"), file );
  menu->insertItem( trans->translate("&Game"), game );
  menu->insertItem( trans->translate("&Options"), options );
  menu->insertSeparator();
  menu->insertItem( trans->translate("&Help"), help );

  menu->show(); 
  setMenu( menu );

  KIconLoader *loader = kapp->getIconLoader();
  QPixmap **pix = new QPixmap*[NROFTYPES];
  pix[0] = new QPixmap();
  *pix[0] = loader->loadIcon( pFNames[0] );
  if (!pix[0]->isNull()) {
    debug( "Pixmap \"%s\" loaded.", pFNames[0] );
    for (i = 1; i < NROFTYPES; i++) {
      pix[i] = new QPixmap;
      *pix[i] = loader->loadIcon( pFNames[i] );
      if (!pix[i]->isNull()) {
	debug( "Pixmap \"%s\" loaded.", pFNames[i] );
      } else {
	pix[i] = pix[i-1];
	pix[i]->detach();
	debug( "Cannot find pixmap \"%s\". Using previous one.", pFNames[i] );
      }
    }
  } else {
    debug( "Cannot find pixmap \"%s\". Pixmaps will not be loaded.",
	   pFNames[0] );
    delete pix[0];
    delete pix;
    pix = NULL;
  }
  gr = new KBBGraphic( pix, this );
  connect( gr, SIGNAL(inputAt(int,int,int)),
	  this, SLOT(gotInputAt(int,int,int)) );
  connect( this, SIGNAL(gameRuns(bool)),
	  gr, SLOT(setInputAccepted(bool)) );
  connect( gr, SIGNAL(endMouseClicked()),
	  this, SLOT(gameFinished()) );
  
  /*
  QToolTip::add( doneButton, trans->translate(
		 "Click here when you think you placed all the balls.") );
		 */

  QString tmps;
  stat = new KStatusBar( this );
  tmps.sprintf( "aaaaaaaa" );
  stat->insertItem( (const char *) tmps, SSCORE );
  tmps.sprintf( "aaaaaaaaaaa" );
  stat->insertItem( (const char *) tmps, SBALLS );
  tmps.sprintf( "aaaaaaa" );
  stat->insertItem( (const char *) tmps, SRUN );
  tmps.sprintf( "aaaaaaaaaa" );
  stat->insertItem( (const char *) tmps, SSIZE );
  setStatusBar( stat );

  tool = new KToolBar( this );
  tool->insertButton( loader->loadIcon("exit.xpm"),
		      ID_QUIT, TRUE, trans->translate("Quit") );
  tool->insertButton( loader->loadIcon("reload.xpm"),
		      ID_NEW, TRUE, trans->translate("New") );
  tool->insertButton( loader->loadIcon("giveup.xpm"),
		      ID_GIVEUP, TRUE, trans->translate("Give up") );
  tool->insertButton( loader->loadIcon("done.xpm"),
		      ID_DONE, TRUE, trans->translate("Done") );
  tool->insertSeparator();
  tool->insertButton( loader->loadIcon("help.xpm"), ID_HELP, TRUE,
		      trans->translate("Help") );
  connect( tool, SIGNAL(clicked(int)), SLOT(callBack(int)) );
  addToolBar( tool );
  tool->setBarPos( KToolBar::Top );
  tool->show();
  
  /*
     Game initializations
  */
  running = FALSE;
  gameBoard = NULL;

  KConfig *kConf;
  int j;
  kConf = KApplication::getKApplication()->getConfig();
  kConf->setGroup( "KBlackBox Setup" );
  if (kConf->hasKey( "Balls" )) {
    i = kConf->readNumEntry( "Balls" );
    balls = i;
    switch (i) {
    case 4: ballsm->setItemChecked( balls1id, TRUE ); break;
    case 6: ballsm->setItemChecked( balls2id, TRUE ); break;
    case 8: ballsm->setItemChecked( balls3id, TRUE ); break;
    }
  } else {
    balls = 4;
    ballsm->setItemChecked( balls1id, TRUE );
  }
  if ((kConf->hasKey( "Width" )) &&
      (kConf->hasKey( "Balls" ))) {
    i = kConf->readNumEntry( "Width" );
    j = kConf->readNumEntry( "Height" );
    gr->setSize( i+4, j+4 ); // +4 is the space for "lasers" and an edge...
    gameBoard = new RectOnArray( gr->numC(), gr->numR() );
    switch (i) {
    case 8: sizesm->setItemChecked( sizes1id, TRUE ); break;
    case 10: sizesm->setItemChecked( sizes2id, TRUE ); break;
    case 12: sizesm->setItemChecked( sizes3id, TRUE ); break;
    }
  } else {
    gr->setSize( 8+4, 8+4 ); // +4 is the space for "lasers" and an edge...
    gameBoard = new RectOnArray( gr->numC(), gr->numR() );
    sizesm->setItemChecked( sizes1id, TRUE );
  }
  if (kConf->hasKey( "tutorial" )) {
    tutorial = (bool) kConf->readNumEntry( "tutorial" );
  } else tutorial = FALSE;
  options->setItemChecked( tut1id, tutorial );

  QString s, s1;
  int pos;
  setMinSize();
  gameResize();
  if (kConf->hasKey( "appsize" )) {
    s = kConf->readEntry( "appsize" );
    debug("%s", (const char *) s);
    pos = s.find( 'x' );
    s1 = s.right( s.length() - pos - 1 );
    s.truncate( pos - 1 );
    //    debug("%s", (const char *) s);
    //    debug("%s", (const char *) s1);
    resize( s.toInt(), s1.toInt() );
  }

  setScore( 0 );
  ballsPlaced = 0;
  updateStats();

  setView( gr );

  newGame();
}
Пример #25
0
Window::Window() {
    m_board = new Board(this);
    connect(m_board, &Board::finished, this, &Window::gameFinished);
    connect(m_board, &Board::started, this, &Window::gameStarted);
    connect(m_board, &Board::pauseChanged, this, &Window::gamePauseChanged);

    QWidget* contents = new QWidget(this);
    setCentralWidget(contents);

    View* view = new View(m_board, contents);

    m_scores = new ScoreBoard(this);

    m_definitions = new Definitions(m_board->words(), this);
    connect(m_board, &Board::wordAdded, m_definitions, &Definitions::addWord);
    connect(m_board, &Board::wordSolved, m_definitions, &Definitions::solveWord);
    connect(m_board, &Board::wordSelected, m_definitions, &Definitions::selectWord);
    connect(m_board, &Board::loading, m_definitions, &Definitions::clear);

    // Create success message
    m_success = new QLabel(contents);
    m_success->setAttribute(Qt::WA_TransparentForMouseEvents);

    QFont f = font();
    f.setPointSize(24);
    QFontMetrics metrics(f);
    int width = metrics.width(tr("Success"));
    int height = metrics.height();
    int ratio = devicePixelRatio();
    QPixmap pixmap(QSize(width + height, height * 2) * ratio);
    pixmap.setDevicePixelRatio(ratio);
    pixmap.fill(QColor(0, 0, 0, 0));
    {
        QPainter painter(&pixmap);

        painter.setPen(Qt::NoPen);
        painter.setBrush(QColor(0, 0, 0, 200));
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.drawRoundedRect(0, 0, width + height, height * 2, 10, 10);

        painter.setFont(f);
        painter.setPen(Qt::white);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
        painter.drawText(height / 2, height / 2 + metrics.ascent(), tr("Success"));
    }
    m_success->setPixmap(pixmap);
    m_success->hide();
    connect(m_board, &Board::loading, m_success, &QLabel::hide);

    // Create overlay background
    QLabel* overlay = new QLabel(this);

    f = font();
    f.setPixelSize(20);
    metrics = QFontMetrics(f);
    width = std::max(metrics.width(tr("Loading")), metrics.width(tr("Paused")));
    for (int i = 0; i < 10; ++i) {
        QString test(6, QChar(i + 48));
        test.insert(4, QLatin1Char(':'));
        test.insert(2, QLatin1Char(':'));
        width = std::max(width, metrics.width(test));
    }
    pixmap = QPixmap(QSize(width + 82, 32) * ratio);
    pixmap.setDevicePixelRatio(ratio);
    pixmap.fill(Qt::transparent);
    {
        QPainter painter(&pixmap);

        painter.setPen(Qt::NoPen);
        painter.setBrush(QColor(0, 0, 0, 200));
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.drawRoundedRect(0, -32, width + 82, 64, 5, 5);
    }
    overlay->setPixmap(pixmap);

    // Create overlay buttons
    m_definitions_button = new QLabel(overlay);
    m_definitions_button->setPixmap(QIcon(":/definitions.png").pixmap(24,24));
    m_definitions_button->setCursor(Qt::PointingHandCursor);
    m_definitions_button->setToolTip(tr("Definitions"));
    m_definitions_button->installEventFilter(this);

    m_hint_button = new QLabel(overlay);
    m_hint_button->setPixmap(QIcon(":/hint.png").pixmap(24,24));
    m_hint_button->setCursor(Qt::PointingHandCursor);
    m_hint_button->setToolTip(tr("Hint"));
    m_hint_button->setDisabled(true);
    m_hint_button->installEventFilter(this);
    connect(m_board, &Board::hintAvailable, m_hint_button, &QLabel::setEnabled);

    // Create clock
    m_clock = new Clock(overlay);
    m_clock->setDisabled(true);
    connect(m_clock, &Clock::togglePaused, m_board, &Board::togglePaused);
    connect(m_board, &Board::loading, m_clock, &Clock::setLoading);

    QHBoxLayout* overlay_layout = new QHBoxLayout(overlay);
    overlay_layout->setMargin(0);
    overlay_layout->setSpacing(0);
    overlay_layout->addSpacing(10);
    overlay_layout->addWidget(m_definitions_button);
    overlay_layout->addStretch();
    overlay_layout->addWidget(m_clock, 0, Qt::AlignCenter);
    overlay_layout->addStretch();
    overlay_layout->addWidget(m_hint_button);
    overlay_layout->addSpacing(10);

    // Lay out board
    QGridLayout* layout = new QGridLayout(contents);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(view, 0, 0);
    layout->addWidget(m_success, 0, 0, Qt::AlignCenter);
    layout->addWidget(overlay, 0, 0, Qt::AlignHCenter | Qt::AlignTop);

    // Create menus
    QMenu* menu = menuBar()->addMenu(tr("&Game"));
    menu->addAction(tr("&New"), this, SLOT(newGame()), QKeySequence::New);
    menu->addAction(tr("&Choose..."), this, SLOT(chooseGame()));
    menu->addSeparator();
    m_pause_action = menu->addAction(tr("&Pause"), m_board, SLOT(togglePaused()), tr("P"));
    m_pause_action->setDisabled(true);
    QAction* action = menu->addAction(tr("&Hint"), m_board, SLOT(showHint()), tr("H"));
    action->setDisabled(true);
    connect(m_board, &Board::hintAvailable, action, &QAction::setEnabled);
    menu->addAction(tr("D&efinitions"), m_definitions, SLOT(selectWord()), tr("D"));
    menu->addSeparator();
    menu->addAction(tr("&Details"), this, SLOT(showDetails()));
    menu->addAction(tr("&Scores"), m_scores, SLOT(exec()));
    menu->addSeparator();
    action = menu->addAction(tr("&Quit"), qApp, SLOT(quit()), QKeySequence::Quit);
    action->setMenuRole(QAction::QuitRole);

    menu = menuBar()->addMenu(tr("&Settings"));
    menu->addAction(tr("Application &Language..."), this, SLOT(setLocale()));

    menu = menuBar()->addMenu(tr("&Help"));
    action = menu->addAction(tr("&About"), this, SLOT(about()));
    action->setMenuRole(QAction::AboutRole);
    action = menu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
    action->setMenuRole(QAction::AboutQtRole);

    // Restore window geometry
    QSettings settings;
    resize(800, 600);
    restoreGeometry(settings.value("Geometry").toByteArray());

    // Continue previous or start new game
    show();
    if (settings.contains("Current/Words") && (settings.value("Current/Version" ).toInt() == 4)) {
        m_board->openGame();
    } else {
        settings.remove("Current");
        newGame();
    }
}
Пример #26
0
	void HexagonGame::changeLevel(const string& mId, bool mFirstTime) { newGame(mId, mFirstTime, difficultyMult); }
Пример #27
0
/**
 * Creates a new game in Beginner difficulty and
 * jumps to the Geoscape screen.
 * @param action Pointer to an action.
 */
void NewGameState::btnBeginnerClick(Action *action)
{
	newGame(DIFF_BEGINNER);
}
Пример #28
0
 /* MAIN TESTING FUNCTION */
 int main() {
   struct gameState* state;
   int player = 0;
   int cardsInDeck, cardsInDiscard;

   // play smithy with more than 3 cards in deck, 0 in discard
   state = newGame();
   cardsInDeck = 4;
   cardsInDiscard = 0;
   deck_setup(state, player, cardsInDeck, cardsInDiscard);
   play_smithy(player, state, 0);
   printf("Testing SMITHY CARD with more than 3 cards in deck.\n");
   #if (VERBOSE == 1)
     printf("Expected Cards in Deck: %d | Actual: %d\n", cardsInDeck - 3, state->deckCount[player]);
     printf("Expected Cards in Discard: %d | Actual: %d\n", cardsInDiscard + 1, state->discardCount[player]);
     printf("Expected Cards in Hand: %d | Actual: %d\n", 3, state->handCount[player]);
     printf("Expected # Actions: %d | Actual: %d\n", 0, state->numActions);
     printf("Expected # Buys: %d | Actual: %d\n", 1, state->numBuys);
   #endif
   assert(state->deckCount[player] == cardsInDeck - 3);
   assert(state->discardCount[player] == cardsInDiscard + 1);
   assert(state->handCount[player] == 3);
   assert(state->numActions == 0);
   assert(state->numBuys == 1);
   printf(" - PASSED\n");

   // play smithy with exactly 3 cards in deck, 0 in discard
   state = newGame();
   cardsInDeck = 3;
   cardsInDiscard = 0;
   deck_setup(state, player, cardsInDeck, cardsInDiscard);
   play_smithy(player, state, 0);
   printf("Testing SMITHY CARD with exactly 3 cards in deck.\n");
   #if (VERBOSE == 1)
     printf("Expected Cards in Deck: %d | Actual: %d\n", cardsInDeck - 3, state->deckCount[player]);
     printf("Expected Cards in Discard: %d | Actual: %d\n", cardsInDiscard + 1, state->discardCount[player]);
     printf("Expected Cards in Hand: %d | Actual: %d\n", 3, state->handCount[player]);
     printf("Expected # Actions: %d | Actual: %d\n", 0, state->numActions);
     printf("Expected # Buys: %d | Actual: %d\n", 1, state->numBuys);
   #endif
   assert(state->deckCount[player] == cardsInDeck - 3);
   assert(state->discardCount[player] == cardsInDiscard + 1);
   assert(state->handCount[player] == 3);
   assert(state->numActions == 0);
   assert(state->numBuys == 1);
   printf(" - PASSED\n");

   // play smithy with only 1 card in deck, 2 cards in discard
   // expect that game shuffles cards from discard back into deck
   state = newGame();
   cardsInDeck = 1;
   cardsInDiscard = 2;
   deck_setup(state, player, cardsInDeck, cardsInDiscard);
   play_smithy(player, state, 0);
   printf("Testing SMITHY CARD with the need to shuffle discard into deck.\n");
   #if (VERBOSE == 1)
     printf("Expected Cards in Deck: %d | Actual: %d\n", ((cardsInDeck + cardsInDiscard) - 3), state->deckCount[player]);
     printf("Expected Cards in Discard: %d | Actual: %d\n", 1, state->discardCount[player]);
     printf("Expected Cards in Hand: %d | Actual: %d\n", 3, state->handCount[player]);
     printf("Expected # Actions: %d | Actual: %d\n", 0, state->numActions);
     printf("Expected # Buys: %d | Actual: %d\n", 1, state->numBuys);
   #endif
   assert(state->deckCount[player] == ((cardsInDeck + cardsInDiscard) - 3));
   assert(state->discardCount[player] == 1);
   assert(state->handCount[player] == 3);
   assert(state->numActions == 0);
   assert(state->numBuys == 1);
   printf(" - PASSED\n");

   printf("\nAll tests passed.\n\n");
   return 0;
 }
Пример #29
0
/**
 * Creates a new game in Veteran difficulty and
 * jumps to the Geoscape screen.
 * @param action Pointer to an action.
 */
void NewGameState::btnVeteranClick(Action *action)
{
	newGame(DIFF_VETERAN);
}
Пример #30
0
ConnectFour::ConnectFour(NESController *controller, Adafruit_WS2801 *strip,LCD *lcdIn):Game(controller, strip, lcdIn){
	newGame();
}