示例#1
0
int main() {
	char playAgain;

	do {
		nodes_expanded = 0;
		//initialize the board.
		char *board = newBoard();

		//get player and computer characters.
		char playerPiece = askUser("\nPlease choose your character (x or o): ", X, O);
		char computerPiece = getOpponentPiece(playerPiece);

		//check if player wants to play first.
		char ch = askUser("\nDo you want to play first ? (y or n): ", 'y', 'n');
		if(ch == 'y') {
			makePlayerMove(board, playerPiece);			
		}
		else if(ch == 'n') {
		}

		char winner;
		int turn = COMPUTER;

		//game loop.
		while(!isFilled(board) && (winner = whoWon(board)) == NONE) {

			if(turn == COMPUTER) {
				makeComputerMove(board, computerPiece);
				turn = PLAYER;
			}
			else {
				makePlayerMove(board, playerPiece);
				turn = COMPUTER;
			}
		}

		printBoard(board);

		//print results.
		if(winner == playerPiece) {
			printf("\n$ Congratulations! you have won. $\n");
		}
		else if(winner == NONE) {
			printf("\n* The game is a draw. *\n");
		}
		else {
			printf("\n@ You Lose!! @\n");
		}

		printf("\nNumber of nodes expanded: %d", nodes_expanded);

		//ask if user wants to play again.
		playAgain = askUser("\n Do you want to play again? (y or n): ", 'y', 'n');
	}while(playAgain == 'y');

	return 0;
}
示例#2
0
void displayMenu()
{
	char choice;

	system("cls");
	printf("[1]-DISPLAY ALL\n[a]-NEXT\n[d]-PREVIOUS\n");
	printf("PRESS ESC TO RETURN TO MAIN MENU...\n");
	choice=getch();

	switch(choice)
	{
		case '1':
			displayArray();
			getch();
			displayMenu();
			break;
		case 'a':
			nextItem();
			getch();
			displayMenu();
			break;
		case 'd':
			prevItem();
			getch();
			displayMenu();
			break;
		default:
			askUser();	
			break;
	}
}
示例#3
0
void PerformCopyTask::askForOverwrite(const QString &text, volatile bool &tryAgain, const volatile Flags &aborted)
{
	qint32 answer = askUser(
						tr("Extracting..."),
						text,
						QMessageBox::Yes |
						QMessageBox::YesToAll |
						QMessageBox::No |
						QMessageBox::NoToAll |
						QMessageBox::Cancel,
						aborted);

	switch (answer)
	{
		case QMessageBox::Yes:
			tryAgain = true;
			break;

		case QMessageBox::YesToAll:
			m_overwriteAll = tryAgain = true;
			break;

		case QMessageBox::No:
			tryAgain = false;
			break;

		case QMessageBox::NoToAll:
			m_overwriteAll = tryAgain = false;
			break;

		case QMessageBox::Cancel:
			cancel();
			break;
	}
}
示例#4
0
// dispatcher code for entering one of the available states
void PlanExecutor::enterAvailableState() {
	if(mState == NOT_AVAILABLE) {
		mShowFilesAction->setEnabled(true);
		mRunBackupAction->setEnabled(true);
		mActionMenu->setEnabled(true);
		mState = WAITING_FOR_FIRST_BACKUP; //initial child state of "Available" state
		emit stateChanged();
	}

	bool lShouldBeTakenNow = false;
	bool lShouldBeTakenLater = false;
	int lTimeUntilNextWakeup;
	QString lUserQuestion;
	QDateTime lNow = QDateTime::currentDateTime().toUTC();

	switch(mPlan->mScheduleType) {
	case BackupPlan::MANUAL:
		break;
	case BackupPlan::INTERVAL: {
		QDateTime lNextTime = mPlan->nextScheduledTime();
		if(!lNextTime.isValid() || lNextTime < lNow) {
			lShouldBeTakenNow = true;
			if(!mPlan->mLastCompleteBackup.isValid())
				lUserQuestion = i18nc("@info", "Do you want to take a first backup now?");
			else {
				QString t = KGlobal::locale()->prettyFormatDuration(mPlan->mLastCompleteBackup.secsTo(lNow) * 1000);
				lUserQuestion = i18nc("@info", "It's been %1 since the last backup was taken, "
				                     "do you want to take a backup now?", t);
			}
		} else {
			lShouldBeTakenLater = true;
			lTimeUntilNextWakeup = lNow.secsTo(lNextTime)*1000;
		}
		break;
	}
	case BackupPlan::USAGE:
		if(!mPlan->mLastCompleteBackup.isValid()) {
			lShouldBeTakenNow = true;
			lUserQuestion = i18nc("@info", "Do you want to take a first backup now?");
		} else if(mPlan->mAccumulatedUsageTime > (quint32)mPlan->mUsageLimit * 3600) {
			lShouldBeTakenNow = true;
			QString t = KGlobal::locale()->prettyFormatDuration(mPlan->mAccumulatedUsageTime * 1000);
			lUserQuestion = i18nc("@info", "You've been active with this computer for %1 since the last backup was taken, "
			                     "do you want to take a backup now?", t);
		}
		break;
	}

	if(lShouldBeTakenNow) {
		// only ask the first time after destination has become available
		if(mPlan->mAskBeforeTakingBackup && mState == WAITING_FOR_FIRST_BACKUP) {
			askUser(lUserQuestion);
		} else {
			enterBackupRunningState();
		}
	} else if(lShouldBeTakenLater){
		// schedule a wakeup for asking again when the time is right.
		mSchedulingTimer->start(lTimeUntilNextWakeup);
	}
}
示例#5
0
// dispatcher code for entering one of the available states
void PlanExecutor::enterAvailableState() {
	if(mState == NOT_AVAILABLE) {
		mState = WAITING_FOR_FIRST_BACKUP; //initial child state of "Available" state
		emit stateChanged();
	}

	bool lShouldBeTakenNow = false;
	bool lShouldBeTakenLater = false;
	int lTimeUntilNextWakeup;
	QString lUserQuestion;
	QDateTime lNow = QDateTime::currentDateTime().toUTC();

	switch(mPlan->mScheduleType) {
	case BackupPlan::MANUAL:
		break;
	case BackupPlan::INTERVAL: {
		QDateTime lNextTime = mPlan->nextScheduledTime();
		if(!lNextTime.isValid() || lNextTime < lNow) {
			lShouldBeTakenNow = true;
			if(!mPlan->mLastCompleteBackup.isValid())
				lUserQuestion = xi18nc("@info", "Do you want to save a first backup now?");
			else {
				QString t = KFormat().formatSpelloutDuration(mPlan->mLastCompleteBackup.secsTo(lNow) * 1000);
				lUserQuestion = xi18nc("@info", "It has been %1 since last backup was saved.\n"
				                                "Save a new backup now?", t);
			}
		} else {
			lShouldBeTakenLater = true;
			lTimeUntilNextWakeup = lNow.secsTo(lNextTime)*1000;
		}
		break;
	}
	case BackupPlan::USAGE:
		if(!mPlan->mLastCompleteBackup.isValid()) {
			lShouldBeTakenNow = true;
			lUserQuestion = xi18nc("@info", "Do you want to save a first backup now?");
		} else if(mPlan->mAccumulatedUsageTime > (quint32)mPlan->mUsageLimit * 3600) {
			lShouldBeTakenNow = true;
			QString t = KFormat().formatSpelloutDuration(mPlan->mAccumulatedUsageTime * 1000);
			lUserQuestion = xi18nc("@info", "You have been active for %1 since last backup was saved.\n"
			                                "Save a new backup now?", t);
		}
		break;
	}

	if(lShouldBeTakenNow) {
		// Only ask the first time after destination has become available.
		// Always ask if power saving is active.
		if( (mPlan->mAskBeforeTakingBackup && mState == WAITING_FOR_FIRST_BACKUP) ||
		    powerSaveActive()) {
			askUser(lUserQuestion);
		} else {
			startBackupSaveJob();
		}
	} else if(lShouldBeTakenLater){
		// schedule a wakeup for asking again when the time is right.
		mSchedulingTimer->start(lTimeUntilNextWakeup);
	}
}
/** Read a transaction from the stream, parse it and ask the user
  * if they approve it.
  * \param out_approved A non-zero value will be written to here if the
  *                     user approved the transaction, otherwise a zero value
  *                     will be written.
  * \param sig_hash The signature hash of the transaction will be written to
  *                 here by parseTransaction(). This must be an array of 32
  *                 bytes.
  * \param transaction_length The length of the transaction, in number of
  *                           bytes. This can be derived from the payload
  *                           length of a packet.
  */
static NOINLINE void parseTransactionAndAsk(uint8_t *out_approved, uint8_t *sig_hash, uint32_t transaction_length)
{
	TransactionErrors r;
	uint8_t transaction_hash[32];

	// Validate transaction and calculate hashes of it.
	*out_approved = 0;
	clearOutputsSeen();
	r = parseTransaction(sig_hash, transaction_hash, transaction_length);
	if (r != TRANSACTION_NO_ERROR)
	{
		// Transaction parse error.
		writeString(STRINGSET_TRANSACTION, (uint8_t)r, PACKET_TYPE_FAILURE);
		return;
	}

	// Get permission from user.
	*out_approved = 0;
	// Does transaction_hash match previous approved transaction?
	if (prev_transaction_hash_valid)
	{
		if (bigCompare(transaction_hash, prev_transaction_hash) == BIGCMP_EQUAL)
		{
			*out_approved = 1;
			prev_transaction_hash_valid--;
		}
	}
	if (!(*out_approved))
	{
		// Need to explicitly get permission from user.
		// The call to parseTransaction() should have logged all the outputs
		// to the user interface.
		if (askUser(ASKUSER_SIGN_TRANSACTION))
		{
			writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
		}
		else
		{
			// User approved transaction.
			*out_approved = 1;
			memcpy(prev_transaction_hash, transaction_hash, 32);
			// The transaction hash can only be reused another
			// (number of inputs) - 1 times. This is to prevent an exploit
			// where an attacker crafts a lot of copies (with differing inputs
			// but identical outputs) of a genuine transaction. With unlimited
			// reuse of the transaction hash, acceptance of the original
			// genuine transaction would also allow all the copies to be
			// automatically accepted, causing the user to spend more than
			// they intended.
			prev_transaction_hash_valid = getTransactionNumInputs();
			if (prev_transaction_hash_valid)
			{
				prev_transaction_hash_valid--;
			}
		}
	} // if (!(*out_approved))
}
示例#7
0
int validateUser() {
    int length = 50;
    char login[length * 2 + 2];
    askUser("User: "******":");
    askUser("Password: "******"TEST: %s CORRECT: %s RES: %d\n", login, passwords[i], result);
      if(result == 0)
        return 1;
    }
    return 0;
}
示例#8
0
// creates new file
void WMain::newfile() {
	if(cDocument->filechanged) {
		int userAnswer = askUser(tr("File has been changed. Save?"));
		if(userAnswer == 2) saveFileAction();
		else if(userAnswer == 1) return;
	}
	
	delete cDocument;
	cDocument = new CDocument;
	updateList();
	updateStatusbar();
}
示例#9
0
// opens file
void WMain::openfile(QString filename) {
	if(cDocument->filechanged) {
		int userAnswer = askUser(tr("File has been changed. Save?"));
		if(userAnswer == 2) {
			saveFileAction();
			openFileAction(filename);
		}
		else if(userAnswer == 1) return;
		else openFileAction(filename);
		}
	else
		openFileAction(filename);
}
示例#10
0
void askUser()
{
	char choice;
	int x;
	int loop;
	
	system("cls");
	printf("---MAIN MENU---\n");
	printf("\n[1]-ENTER STRING\n[2]-DISPLAY\n[3]-SORT\n\n");
	choice=getch();

	switch(choice)
	{
		case '1':
			printf("How many number(s)?");
			scanf("%d",&loop);
			
			for(x=0;x<loop;x++)
				askStr();
				
			getch();
			askUser();
			break;
		case '2':
			displayMenu();
			getch();
			askUser();
			break;
		case '3':
			sortMenu();
			getch();
			askUser();
			break;
		default:
			getch();
			break;	
	}	
}
示例#11
0
// window close event
void WMain::closeEvent(QCloseEvent * e) {
	if(cDocument->filechanged) {
		int userAnswer = askUser(tr("File has been changed. Save?"));
		if (userAnswer == 2) {
			saveFileAction();
			application->quit();
			e->accept();
		}
		else if(userAnswer == 1) e->ignore();
		else if(userAnswer == 0) {
			e->accept();
			application->quit();
		}
		else e->ignore();
		return;
	}
	else
		application->quit();
}
bool UnPackIntoSubdirActionTask::askForSkipIfNotCopy(const QString &error, bool &flag, const volatile Flags &aborted)
{
    qint32 answer = askUser(
                        tr("Extracting..."),
                        QString(error).append(L'\n').append(tr("Skip it?")),
                        QMessageBox::Yes |
                        QMessageBox::YesToAll |
                        QMessageBox::Retry |
                        QMessageBox::Cancel,
                        aborted);

    if (answer == QMessageBox::YesToAll)
        flag = true;
    else if (answer == QMessageBox::Retry)
        return true;
    else if (answer == QMessageBox::Cancel)
        cancel();

    return false;
}
示例#13
0
void PerformCopyTask::askForSkipIfNotCopy(const QString &text, volatile bool &tryAgain, const volatile Flags &aborted)
{
	qint32 answer = askUser(
						tr("Extracting..."),
						text,
						QMessageBox::Yes |
						QMessageBox::YesToAll |
						QMessageBox::Retry |
						QMessageBox::Cancel,
						aborted);

	if (answer == QMessageBox::YesToAll)
		m_skipAllIfNotCopy = true;
	else
		if (answer == QMessageBox::Retry)
			tryAgain = true;
		else
			if (answer == QMessageBox::Cancel)
				cancel();
}
示例#14
0
	bool testPasswordStrength(std::string &rPassword, mySafeCore::ImySafeCore * pMySafeCore, std::istream &rInput, std::ostream &rOutput, CCommandParser const &rCommandParser)
	{
		bool IsPasswordStrong = false;

		int Strength = pMySafeCore->getPasswordStrength(rPassword, "");

	  if (Strength < 75)
		{
			IsPasswordStrong = false;
		  rOutput << "[WARNING] Password strength is: " << getStrengthString(Strength).c_str() << " (" << Strength << "%)" << std::endl;

			if (rCommandParser.isNotInteractive())
			{
				throw ExInputError("Used password is too weak in not-interactive mode. Please specify a stronger password.", 1);
			}

			if (askUser(rInput, rOutput, rCommandParser, std::string("Do you want to chose another password?")) == true)
			{
				rPassword = "";
			}
			else
			{
				IsPasswordStrong = true;
			}
		}
		else
		{
			IsPasswordStrong = true;

			if (!rCommandParser.isSilent())
			{
			  rOutput << "Password strength is: " << getStrengthString(Strength).c_str() << std::endl;
			}
		}

		return IsPasswordStrong;
	}
示例#15
0
void askUser()
{
	int num;
	int x=10;
	int i;
	char choices;
	
	struct node *current;
	current=head;
	
	system("cls");
	printf("\n[1]-ENQUEUE\n[2]-DEQUEUE\n[3]-FRONT\n[4]-REAR\n");
	choices=getch();

	switch(choices)
	{
		case '1':
			num=askNum();
			for(i=0;i<num;i++)
			{
				while(x<0||x>9)
				{
					printf("Enter number: ");
					scanf("%d",&x);
				}
				insertRear(x);
				x=10;
				displayArray();
			}
			getch();
			askUser();
			break;
		case '2':
			deleteFront();
			displayArray();
			getch();
			askUser();
			break;
		case '3':
			if(head!=NULL)
			{
				printf("%d",head->data);
			}
			else
			{
				printf("List is empty");
			}
			getch();
			askUser();
			break;
		case '4':
			while(current->next!=NULL)
			{
				current=current->next;
			}
			printf("%d",current->data);
			getch();
			askUser();
			break;
		default:
			getch();
			break;
	}
}
示例#16
0
void main()
{
	head=NULL;
	askUser();
}
示例#17
0
// cancels test
void WMain::canceltest() {
	int userAnswer = askUser(tr("Are you sure to cancel test?"));
	if(userAnswer == 2) endTest(false);
	else if(userAnswer == 1) return;
	else return;
}
/** Get packet from stream and deal with it. This basically implements the
  * protocol described in the file PROTOCOL.
  * 
  * This function will always completely
  * read a packet before sending a response packet. As long as the host
  * does the same thing, deadlocks cannot occur. Thus a productive
  * communication session between the hardware Bitcoin wallet and a host
  * should consist of the wallet and host alternating between sending a
  * packet and receiving a packet.
  */
void processPacket(void)
{
	uint8_t command;
	// Technically, the length of buffer should also be >= 4, since it is used
	// in a couple of places to obtain 32 bit values. This is guaranteed by
	// the reference to WALLET_ENCRYPTION_KEY_LENGTH, since no-one in their
	// right mind would use encryption with smaller than 32 bit keys.
	uint8_t buffer[MAX(NAME_LENGTH, WALLET_ENCRYPTION_KEY_LENGTH)];
	uint32_t num_addresses;
	AddressHandle ah;
	WalletErrors wallet_return;

	command = streamGetOneByte();
	getBytesFromStream(buffer, 4);
	payload_length = readU32LittleEndian(buffer);

	// Checklist for each case:
	// 1. Have you checked or dealt with length?
	// 2. Have you fully read the input stream before writing (to avoid
	//    deadlocks)?
	// 3. Have you asked permission from the user (for potentially dangerous
	//    operations)?
	// 4. Have you checked for errors from wallet functions?
	// 5. Have you used the right check for the wallet functions?

	switch (command)
	{

	case PACKET_TYPE_PING:
		// Ping request.
		// Just throw away the data and then send response.
		readAndIgnoreInput();
		writeString(STRINGSET_MISC, MISCSTR_VERSION, PACKET_TYPE_PING_REPLY);
		break;

	// Commands PACKET_TYPE_PING_REPLY, PACKET_TYPE_SUCCESS and
	// PACKET_TYPE_FAILURE should never be received; they are only sent.

	case PACKET_TYPE_NEW_WALLET:
		// Create new wallet.
		if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH + NAME_LENGTH))
		{
			getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
			setEncryptionKey(buffer);
			getBytesFromStream(buffer, NAME_LENGTH);
			if (askUser(ASKUSER_NUKE_WALLET))
			{
				writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
			}
			else
			{
				wallet_return = newWallet(buffer);
				translateWalletError(wallet_return, 0, NULL);
			}
		}
		break;

	case PACKET_TYPE_NEW_ADDRESS:
		// Create new address in wallet.
		if (!expectLength(0))
		{
			if (askUser(ASKUSER_NEW_ADDRESS))
			{
				writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
			}
			else
			{
				getAndSendAddressAndPublicKey(1);
			}
		}
		break;

	case PACKET_TYPE_GET_NUM_ADDRESSES:
		// Get number of addresses in wallet.
		if (!expectLength(0))
		{
			num_addresses = getNumAddresses();
			writeU32LittleEndian(buffer, num_addresses);
			wallet_return = walletGetLastError();
			translateWalletError(wallet_return, 4, buffer);
		}
		break;

	case PACKET_TYPE_GET_ADDRESS_PUBKEY:
		// Get address and public key corresponding to an address handle.
		if (!expectLength(4))
		{
			getAndSendAddressAndPublicKey(0);
		}
		break;

	case PACKET_TYPE_SIGN_TRANSACTION:
		// Sign a transaction.
		if (payload_length <= 4)
		{
			readAndIgnoreInput();
			writeString(STRINGSET_MISC, MISCSTR_INVALID_PACKET, PACKET_TYPE_FAILURE);
		}
		else
		{
			getBytesFromStream(buffer, 4);
			ah = readU32LittleEndian(buffer);
			// Don't need to subtract 4 off payload_length because
			// getBytesFromStream() has already done so.
			validateAndSignTransaction(ah, payload_length);
			payload_length = 0;
		}
		break;

	case PACKET_TYPE_LOAD_WALLET:
		// Load wallet.
		if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH))
		{
			getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
			setEncryptionKey(buffer);
			wallet_return = initWallet();
			translateWalletError(wallet_return, 0, NULL);
		}
		break;

	case PACKET_TYPE_UNLOAD_WALLET:
		// Unload wallet.
		if (!expectLength(0))
		{
			clearEncryptionKey();
			sanitiseRam();
			memset(buffer, 0xff, sizeof(buffer));
			memset(buffer, 0, sizeof(buffer));
			wallet_return = uninitWallet();
			translateWalletError(wallet_return, 0, NULL);
		}
		break;

	case PACKET_TYPE_FORMAT:
		// Format storage.
		if (!expectLength(0))
		{
			if (askUser(ASKUSER_FORMAT))
			{
				writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
			}
			else
			{
				wallet_return = sanitiseNonVolatileStorage(0, 0xffffffff);
				translateWalletError(wallet_return, 0, NULL);
				uninitWallet(); // force wallet to unload
			}
		}
		break;

	case PACKET_TYPE_CHANGE_KEY:
		// Change wallet encryption key.
		if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH))
		{
			getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
			wallet_return = changeEncryptionKey(buffer);
			translateWalletError(wallet_return, 0, NULL);
		}
		break;

	case PACKET_TYPE_CHANGE_NAME:
		// Change wallet name.
		if (!expectLength(NAME_LENGTH))
		{
			getBytesFromStream(buffer, NAME_LENGTH);
			if (askUser(ASKUSER_CHANGE_NAME))
			{
				writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
			}
			else
			{
				wallet_return = changeWalletName(buffer);
				translateWalletError(wallet_return, 0, NULL);
			}
		}
		break;

	case PACKET_TYPE_LIST_WALLETS:
		// List wallets.
		if (!expectLength(0))
		{
			listWallets();
		}
		break;

	default:
		// Unknown command.
		readAndIgnoreInput();
		writeString(STRINGSET_MISC, MISCSTR_INVALID_PACKET, PACKET_TYPE_FAILURE);
		break;

	}

#ifdef TEST_STREAM_COMM
	assert(payload_length == 0);
#endif

}
示例#19
0
void sortMenu()
{
	char choice;
	
	system('cls');
	printf("[1]-INSERTION SORT\n[2]-SELECTION SORT\n[3]-BUBBLE SORT\n[4]-BUCKET SORT\n[5]-HEAP SORT\n[6]-QUICK SORT\n[7]-RADIX SORT\n[8]-COMB SORT\n[9]-MERGE SORT\n[0]-SHELL SORT\n");
	printf("Press any key in order to return to MAIN MENU...");
	choice=getche();
	
	switch(choice)
	{
		case '1':		//insertion
			sortInsert();
			getch();
			sortMenu();
			break;
		case '2':		//selection
			getch();
			sortMenu();
			break;
		case '3':		//bubble
			//bubbleSort(parameter1);
			getch();
			sortMenu();	
			break;
		case '4':		//bucket
			getch();
			sortMenu();
			break;
		case '5':		//heap
			getch();
			sortMenu();
			break;
		case '6':		//quick
			//QuickSortList(parameter1,parameter2);
			getch();
			sortMenu();
			break;
		case '7':		//radix
			getch();
			sortMenu();
			break;
		case '8':		//comb
			getch();
			sortMenu();
			break;
		case '9':		//merge
			//mergesort(parameter1)
			getch();
			sortMenu();
			break;
		case '0':		//shell
			getch();
			sortMenu();
			break;
		default:
			getch();
			askUser();
			break;
	}
}
示例#20
0
文件: main.cpp 项目: cedsam/Cpp
int main () // "Guess the word" game in OCR lessons.
{
		std::string wannaPlay;
		int gameAmounts=0;
		int gameWin=0;
		int defeats=0;
		int attempts=0;

		do 
		{
			bool isGuessedResult = false;
			int numberAttempts=0;
			std::string const dictionnaryDirectory("C:/Users/user/dico.txt");
			std::string word(pickOneWord(dictionnaryDirectory));
			std::string mixedWord (mixtureWord(word));
			std::string guessWord (askUser ("Guess the following word in the correct order: " + mixedWord + " \n"));
			gameAmounts++;

			while (isGuessedResult == false)//int guessResult = 0; ==> wasn't clear enough, replace with isGuessedResult
			{
				if ((guessWord!=word) && (numberAttempts!=4))
				{
					attempts++;
					numberAttempts++;
					guessWord=askUser("You are wrong, try again ");
				}
				else if (guessWord==word)
				{
					gameWin++;
					isGuessedResult = true;
					wannaPlay = (askUser("Wanna play again? [yes/no] "));
				}
				else if ((guessWord!=word) && (numberAttempts==4))
				{
					defeats++;
					isGuessedResult  = true;
					wannaPlay = (askUser("The solution was " + word + ". \n" "Wanna play again? [yes/no] "));
					
					while ((wannaPlay != "no") && (wannaPlay != "n") && (wannaPlay != "yes") && (wannaPlay != "y"))
					{
						wannaPlay = (askUser("Wanna play again? [yes/no] "));
					} 
				}
			}

			word.clear();
			mixedWord.clear();
			guessWord.clear();

			isGuessedResult = true;

		} while ((wannaPlay != "no") && (wannaPlay != "n"));
		gameStatistics(gameAmounts,gameWin,defeats,attempts);

		//clearing all variable.
		wannaPlay.clear();
		gameAmounts = 0;
		gameWin = 0;
		defeats = 0;
		attempts = 0;

		//end of program
		exit(EXIT_SUCCESS);
}
示例#21
0
extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
{
    KLocale::setMainCatalogue("konqueror");
    KAboutData aboutData("keditbookmarks", I18N_NOOP("Bookmark Editor"), VERSION, I18N_NOOP("Konqueror Bookmarks Editor"), KAboutData::License_GPL,
                         I18N_NOOP("(c) 2000 - 2003, KDE developers"));
    aboutData.addAuthor("David Faure", I18N_NOOP("Initial author"), "*****@*****.**");
    aboutData.addAuthor("Alexander Kellett", I18N_NOOP("Author"), "*****@*****.**");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KApplication::addCmdLineOptions();
    KCmdLineArgs::addCmdLineOptions(options);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    bool isGui =
        !(args->isSet("exportmoz") || args->isSet("exportns") || args->isSet("exporthtml") || args->isSet("exportie") || args->isSet("exportopera")
          || args->isSet("importmoz") || args->isSet("importns") || args->isSet("importie") || args->isSet("importopera"));

    bool browser = args->isSet("browser");

    KApplication::disableAutoDcopRegistration();
    KApplication app(isGui, isGui);

    bool gotArg = (args->count() == 1);

    QString filename = gotArg ? QString::fromLatin1(args->arg(0)) : locateLocal("data", QString::fromLatin1("konqueror/bookmarks.xml"));

    if(!isGui)
    {
        CurrentMgr::self()->createManager(filename);
        CurrentMgr::ExportType exportType = CurrentMgr::MozillaExport; // uumm.. can i just set it to -1 ?
        int got = 0;
        const char *arg, *arg2 = 0, *importType = 0;
        if(arg = "exportmoz", args->isSet(arg))
        {
            exportType = CurrentMgr::MozillaExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportns", args->isSet(arg))
        {
            exportType = CurrentMgr::NetscapeExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exporthtml", args->isSet(arg))
        {
            exportType = CurrentMgr::HTMLExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportie", args->isSet(arg))
        {
            exportType = CurrentMgr::IEExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportopera", args->isSet(arg))
        {
            exportType = CurrentMgr::OperaExport;
            arg2 = arg;
            got++;
        }
        if(arg = "importmoz", args->isSet(arg))
        {
            importType = "Moz";
            arg2 = arg;
            got++;
        }
        if(arg = "importns", args->isSet(arg))
        {
            importType = "NS";
            arg2 = arg;
            got++;
        }
        if(arg = "importie", args->isSet(arg))
        {
            importType = "IE";
            arg2 = arg;
            got++;
        }
        if(arg = "importopera", args->isSet(arg))
        {
            importType = "Opera";
            arg2 = arg;
            got++;
        }
        if(!importType && arg2)
        {
            Q_ASSERT(arg2);
            // TODO - maybe an xbel export???
            if(got > 1) // got == 0 isn't possible as !isGui is dependant on "export.*"
                KCmdLineArgs::usage(I18N_NOOP("You may only specify a single --export option."));
            QString path = QString::fromLocal8Bit(args->getOption(arg2));
            CurrentMgr::self()->doExport(exportType, path);
        }
        else if(importType)
        {
            if(got > 1) // got == 0 isn't possible as !isGui is dependant on "import.*"
                KCmdLineArgs::usage(I18N_NOOP("You may only specify a single --import option."));
            QString path = QString::fromLocal8Bit(args->getOption(arg2));
            ImportCommand *importer = ImportCommand::importerFactory(importType);
            importer->import(path, true);
            importer->execute();
            CurrentMgr::self()->managerSave();
            CurrentMgr::self()->notifyManagers();
        }
        return 0; // error flag on exit?, 1?
    }

    QString address = args->isSet("address") ? QString::fromLocal8Bit(args->getOption("address")) : QString("/0");

    QString caption = args->isSet("customcaption") ? QString::fromLocal8Bit(args->getOption("customcaption")) : QString::null;

    args->clear();

    bool readonly = false; // passed by ref

    if(askUser(app, (gotArg ? filename : QString::null), readonly))
    {
        KEBApp *toplevel = new KEBApp(filename, readonly, address, browser, caption);
        toplevel->show();
        app.setMainWidget(toplevel);
        return app.exec();
    }

    return 0;
}
示例#22
0
void askUser()
{
	int num;
	int x=10;
	int i;
	char choices;
	
	system("cls");
	printf("\n[1]-DISPLAY ARRAY\n[2]-INSERT REAR\n[3]-INSERT FRONT\n[4]-INSERT INTO\n[5]-DELETE FRONT\n[6]-DELETE REAR\n[7]-DELETE ITEM\n[8]-DELETE ALL ITEM\n[9]-MAKE UNIQUE\n");
	choices=getch();

	switch(choices)
	{
		case '1':
			displayArray();
			getch();	
			askUser();
			break;
		case '2':
			num=askNum();
			for(i=0;i<num;i++)
			{
				while(x<0||x>9)
				{
					printf("Enter number: ");
					scanf("%d",&x);
				}
				insertRear(x);
				x=10;
				displayArray();
			}
			getch();
			askUser();
			break;
		case '3':
			num=askNum();
			for(i=0;i<num;i++)
			{
				while(x<0||x>9)
				{
					printf("Enter number: ");
					scanf("%d",&x);
				}
				insertFront(x);
				x=10;
				displayArray();
			}
			getch();
			askUser();
			break;
		case '4':
			displayArray();
			insertInto();
			displayArray();
			getch();
			askUser();
			break;
		case '5':
			deleteFront();
			displayArray();
			getch();
			askUser();
			break;
		case '6':
			deleteRear();
			displayArray();
			getch();
			askUser();
			break;
		case '7':
			displayArray();
			deleteItem();
			displayArray();
			getch();
			askUser();
			break;
		case '8':
			displayArray();
			deleteAllItem();
			displayArray();
			getch();
			askUser();
			break;
		case '9':
			displayArray();
			makeUnique();
			displayArray();
			getch();
			askUser();
			break;
		default:
			getch();
			break;
	}
}
示例#23
0
int main() {
    startup();
    updateUsers();
    loadSettings();
    while(!vars::accepted) {
        getmaxyx(stdscr, vars::maxY, vars::maxX);
        erase();
        firstNotice();
        if(!vars::running)
            break;
        refresh();
    }
    vars::noticeText.scroll = 0;
    while(vars::running) {//Main loop
        updateColors();
        updateUsers();
        if((vars::userList.at(vars::yourself).stat == 0) || ((!vars::chatting) && (!vars::banning)) || ((vars::about) && (!vars::settingsChangingDescription) && (!vars::settingsChangingNickname)))
            curs_set(0);
        else
            curs_set(1);
        getmaxyx(stdscr, vars::maxY, vars::maxX);
        erase();
        if((vars::maxX < 80) || (vars::maxY < 20)) {
            printw("The console window size is too small.\nPlease resize it to at least 80 * 20 width and height respectively.\nPress [Esc] or [Ctrl]+[C] to quit if resizing is not possible.");
            if(getch() == 27)
                vars::running = false;
        }
        else {
            printMainframe();
            if(vars::about)
                about();
            else {
                if(vars::menu == 0) {
                    notifications();
                    askUser();
                }
                else if(vars::menu == 1)
                    chatFrame();
            }
		}

        if((vars::previousState != 4) && (vars::previousState != vars::userList.at(vars::yourself).stat)) { //Check if your user stat changed
            curs_set(0);
            unsigned char thisState = vars::userList.at(vars::yourself).stat;
            if((vars::previousState > 0) && (thisState == 0)) {
                broadcast(std::vector < std::string >(1, "You have been banned!"), 6);
                vars::input.clear();
                vars::chattingWith.clear();
                vars::yourStr.clear();
                vars::menu = 0;
                vars::chatting = true;
                vars::chatScroll = -1;
                flushinp();
            }
            else if((vars::previousState == 0) && (thisState == 1))
                broadcast(std::vector < std::string >(1, "You have been unbanned!"), 8);
            else if((vars::previousState == 2) && (thisState == 1))
                broadcast(std::vector < std::string >(1, "You have been demoted!"), 6);
            else if((vars::previousState < 2) && (thisState == 2))
                broadcast(std::vector < std::string >(1, "You have been promoted to moderator!"), 8);
            broadcastWait(10);
        }
        else if(vars::broadcast.size() > 0) { //Or just draw a broadcast to the screen if there is one being sent.
            curs_set(0);
            broadcast(vars::broadcast, 6);
            vars::broadcast.clear();
            broadcastWait(10);
        }
        else {
            parseInput();
            refresh();
        }
        vars::previousState = vars::userList.at(vars::yourself).stat;
    }
    endwin();
    return 0;
}