// Captures keyboard input for GLUT
// Sets variables for doing transforms
void keyboard(unsigned char key, int x, int y)
{
	if (key == 27)
		exit(0);
    if (key == 'm')
        nextHole();
    if (key == 'n')
        prevHole();
}
Exemple #2
0
int main(int argc, char * argv[]) {
	//so many variables :S
	process * waitQueue = NULL; //process waiting to be loaded
	process * memQueue = NULL; //list of processes in memory
	process * endQueue = NULL; //processes that have been laoded three times; if any
	process * workingProc = NULL; //process currently being operated on
	process * tempProc = NULL; //temp variable for swapping
	int i,k; //iterators
	int numLoads = 0; //number of loads completed
	int processes = 0; //number of process currently loaded
	int totalProcesses = 0; //cumulative process loaded across all operations
	int insertIndex = -1; //the index where the process will be put into memory
	int holes = 0; //current number of holes
	int currentHole = 0; //currently selected hole
	int mostSuitedHole = -1; //hole most suited for a process, used only by best/worst fit
	int totalHoles = 0; //total number of holes across all operations
	int memory[128]; //array representing memory
	int memUsage = 0; //amount of memory being used
	int totalMemUsage = 0; //cumulative usage across all operations
	FILE * fp; //file pointer is a file pointer

	for( k = 0; k < 4; k++ ) { //loop once for each memory management method
		//k = 0: first fit; 1: best fit; 2: next fit; 3: worst fit

		for( i = 0; i < 128; i++ ) { //memory initialisation
			memory[i] = 0;
		}
		fp = fopen( argv[1], "r" );
		if( fp == NULL ) { //teriminate if no file was entered on the command line
			printf("No file entered\n");
			return 0;
		}
		waitQueue = readFile(fp);

		if( k == 0 ) { //DEBUG
			print(waitQueue);
			printf("\n");
		} //END DEBUG

		while( waitQueue != NULL && k != 2 ) { //loop until all processes are in memory or have been completed
			workingProc = popFromQueue( &waitQueue ); //pop the next process from the ready queue
			while( insertIndex == -1 ) { //loop until a suitable hole has been found
				if( k == 0 && workingProc->size <= holeSize(memory, currentHole) ) { //first fit, simply if hole fits the process
					insertIndex = currentHole;
				} else if ( k == 1 && workingProc->size <= holeSize(memory, currentHole) ) { //best fit, will rotate throguh all of memory first
					if( mostSuitedHole == -1 ) { //first hole that meets criteria
						mostSuitedHole = currentHole;
					} else if (holeSize(memory, currentHole) < holeSize(memory, mostSuitedHole)) { //curhole is a better fit
						mostSuitedHole = currentHole;
					}
					if( currentHole == nextHole(memory, currentHole)) {
						insertIndex = mostSuitedHole;
					}
				} else if ( k == 3 && workingProc->size <= holeSize(memory, currentHole) ) { //best fit, will rotate throguh all of memory first
					if( mostSuitedHole == -1 ) { //first hole that meets criteria
						mostSuitedHole = currentHole;
					} else if (holeSize(memory, currentHole) > holeSize(memory, mostSuitedHole)) { //curhole is a better fit
						mostSuitedHole = currentHole;
					}
					if( currentHole == nextHole(memory, currentHole)) {
						insertIndex = mostSuitedHole;
					}
				}

				if( k != 2 && currentHole == nextHole(memory, currentHole) && insertIndex == -1 ) { //if no valid hole is found above
					//swap oldest process out
					tempProc = popFromQueue(&memQueue);
					if( tempProc->loaded != 3 ) { //not the third time its been swapped
						waitQueue = addToQueue(waitQueue, tempProc); //send it to the wait list
					} else {
						endQueue = addToQueue(endQueue, tempProc);
					}
					CLEARMEMORY(tempProc->start, tempProc->end); //unset its memory
					processes--;
					memUsage -= tempProc->size;
				}
				if( currentHole == nextHole(memory, currentHole) ) {
					currentHole = 0;
				} else {
					currentHole = nextHole(memory, currentHole);
				}				
			}
			if( k != 2 ) //only if not working under next fit, we reset the chosen hole everytime
				currentHole = 0;
			//a spot has been found
			
			//data tracking
			numLoads++;
			processes++;
			holes = countHoles(memory);
			totalProcesses += processes;
			totalHoles += holes;
			memUsage += workingProc->size;
			totalMemUsage += memUsage;

			//annoucement
			printf("%s loaded, #processes = %d, #holes = %d, %%memusage = %.0f, cumulative %%memusage = %.0f\n", workingProc->name, processes, holes, (float)memUsage / 128.0 * 100, \
				 ((float) totalMemUsage / (float)numLoads) / 128.0 * 100 );


			//inserting process
			workingProc->start = insertIndex;
			workingProc->end = workingProc->start + workingProc->size;
			workingProc->loaded++;
			SETMEMORY(workingProc->start, workingProc->end);
			memQueue = addToQueue( memQueue, workingProc );
			mostSuitedHole = -1;
			insertIndex = -1;
		}

		switch(k) {
			case 0: printf("\nFirst Fit \n"); break;
			case 1: printf("\nBest Fit\n"); break;
			case 2: printf("\nNext Fit - not implemented\n"); break;
			case 3: printf("\nWorst Fit\n"); break;
		}

		printf("Total loads = %d, average #processes = %.1f, average #holes = %.1f, cumulative %%memory = %.0f\n\n", numLoads, (float)totalProcesses / (float)numLoads, \
			(float)totalHoles / (float)numLoads, ((float) totalMemUsage / (float)numLoads / 128.0 * 100) );

		fclose(fp);
		destroyQueue(waitQueue);
		destroyQueue(memQueue);
		destroyQueue(endQueue);

		waitQueue = NULL;
		memQueue = NULL;
		endQueue = NULL;

		numLoads = 0;
		processes = 0;
		totalProcesses = 0; 
		insertIndex = -1; 
		holes = 0;
		currentHole = 0;
		mostSuitedHole = -1; 
		totalHoles = 0;
		memUsage = 0; 
		totalMemUsage = 0;
	}
 
	return 0;
}
// Run by GLUT every [tickspeed] miliseconds
void tick(int in)
{
	
	// Local handles to objects
	Level *currentLevel = levelController->getCurrentLevel();
	Ball *ball = currentLevel->getBall();
	Physics *physics = ball->getPhysics();

	Tile* currentTile = currentLevel->getTile(ball->getCurrentTileID());
    vector<int> borderIDs = currentTile->getNeighborIDs();
    vector<Shape*> borderShapes = currentTile->getBorders()->getInwardShapes();

    vec3 ballPosition = physics->getPosition();

	// Debug -- Highlight current tile
	if (DEBUG_TILE_PAINT)
	{
		currentTile->getShapes()[0]->changeColor(TILE_HIGHLIGHT_COLOR);
		currentTile->getShapes()[0]->reload();
	}

    // Collision with cup
    glm::vec3 ballPos = physics->getPosition();
    glm::vec3 cupPos = currentLevel->getCup()->getPhysics()->getPosition();
    float cupPlaneDist = sqrt(((ballPos.x - cupPos.x)*(ballPos.x - cupPos.x)) + ((ballPos.z - cupPos.z)*(ballPos.z - cupPos.z)));

    if(cupPlaneDist < (CUP_RADIUS - (0.8 * BALL_RADIUS)) && abs(cupPos.y - ballPos.y) <= 1.1*BALL_OFFSET){ // allow for slight error
		//Play SFX for falling in hole
		sound->getEngine()->play2D("sfx/retro_cup.wav");
        //----------------CHANGE TO NEXT HOLE----------------//
        nextHole();
    }

    // Physics and collision calculations
	vec3 newDirection = physics->getDirection(); // used for tile transitions
    if(ballMoving)
	{
		// Check for collision
		if(detectCollisions(currentTile, physics, sound)){
			newDirection = physics->getDirection();
		}

        // Update ball direction
        newDirection = updateBallDirection(levelController, sound);

        // Update current tile
        currentTile = currentLevel->getTile(ball->getCurrentTileID());

        // Update ball speed
        double ballSpeed = physics->getSpeed();
        if(currentTile->getShapes().at(0)->normals()[0] == glm::vec3(0.0,1.0,0.0)){ // flat tile
            if(ballSpeed > 0.01){
                physics->setSpeed(ballSpeed - TILE_DEFAULT_FRICTION);
		        ballSpeed = physics->getSpeed();
            }
            else{
                physics->setSpeed(0.0);
                ballStopped();
            }
        }
        else if(newDirection.y > 0){ // going up hill
            //cout << endl << "UP";
            //cout << "Direction y-value: " << newDirection.y << endl;
            if(ballSpeed > 0.01){
                physics->setSpeed(ballSpeed - (TILE_DEFAULT_FRICTION + (2.0*currentTile->getSlope()*TILE_DEFAULT_FRICTION)));
		        ballSpeed = physics->getSpeed();
            }
        }
        else{ // going down hill
            //cout << endl << "DOWN";
            //cout << "Direction y-value: " << newDirection.y << endl;
            if(ballSpeed <= (100.0/100.1)){
                physics->setSpeed(ballSpeed + TILE_DEFAULT_FRICTION);
            }
            else{ // clmap speed
                ballSpeed = (100.0/100.1);
            }
        }

		// Update ballPosition
		physics->updatePosition();

		// Update shape using velocity
		Shape* ballShape = ball->getShapes().at(0);
		ballShape->translate(physics->getVelocity());

		// Update ball direction
		physics->setDirection(newDirection);

        // Snap ball to correct y value -- hacky
        if(currentTile->getShapes().at(0)->normals()[0] == glm::vec3(0.0,1.0,0.0)){ // flat tile
            if(physics->getPosition().y != (currentTile->getPhysics()->getPosition().y + BALL_OFFSET)){
                // Snap ball shape
                ball->getShapes()[0]->translate(vec3(0.0, -(physics->getPosition().y), 0.0));
                ball->getShapes()[0]->translate(vec3(0.0, (currentTile->getPhysics()->getPosition().y + BALL_OFFSET), 0.0));
                // Update ball physics
                physics->setPosition(vec3(physics->getPosition().x, (currentTile->getPhysics()->getPosition().y + BALL_OFFSET), physics->getPosition().z));
            }
        }
		else{// sloped tile
			float correctY = currentTile->getShapes()[0]->yValueAtPoint(physics->getPosition().x, physics->getPosition().z);
			if(physics->getPosition().y != correctY){
				// Snap ball shape
                ball->getShapes()[0]->translate(vec3(0.0, -(physics->getPosition().y), 0.0));
                ball->getShapes()[0]->translate(vec3(0.0, correctY, 0.0));
                // Update ball physics
				physics->setPositionY(correctY);
			}
		}

        // Reload shape
        ballShape->reload();

    }   
    
	// Update HUD
	currentLevel = levelController->getCurrentLevel();
    updateHUD(currentLevel->getLevelName(), fileIO->getNumHoles(), currentHoleScore, currentLevel->getPar());

	//If controls are enabled (ball not yet launched), then make ball direction equal to launchVector
	if (angleSpinner->enabled)
	{
		float launchAngleRadians = launchAngle * (PI/180);
		launchVector = normalize(vec3(sin(launchAngleRadians), 0.0, cos(launchAngleRadians)));
        updateCamera(physics->getPosition(), launchVector, false);
	}
	else
	{
		updateCamera(physics->getPosition(), physics->getDirection(), true);
	}

	glutTimerFunc(tickSpeed, tick, 0);
}
Exemple #4
0
void Kolf::startNewGame()
{
	NewGameDialog *dialog = 0;
	int firstHole = 1;

	if (loadedGame.isNull())
	{
		dialog = new NewGameDialog(filename.isNull(), dummy, "New Game Dialog");
		if (dialog->exec() != QDialog::Accepted)
			goto end;
	}

	players.clear();
	delete scoreboard;
	scoreboard = new ScoreBoard(dummy, "Score Board");
	layout->addWidget(scoreboard, 1, 0);
	scoreboard->show();

	if (loadedGame.isNull())
	{
		PlayerEditor *curEditor = 0;
		int newId = 1;
		for (curEditor = dialog->players()->first(); curEditor; curEditor = dialog->players()->next(), ++newId)
		{
			players.append(Player());
			players.last().ball()->setColor(curEditor->color());
			players.last().setName(curEditor->name());
			players.last().setId(newId);
		}

		competition = dialog->competition();
		filename = filename.isNull()? dialog->course() : filename;
	}
	else
	{
		KConfig config(loadedGame);
		config.setGroup("0 Saved Game");

		if (isTutorial)
			filename = KGlobal::dirs()->findResource("appdata", "tutorial.kolf");
		else
			filename = config.readEntry("Course", QString::null);

		if (filename.isNull())
			return;

		competition = config.readBoolEntry("Competition", false);
		firstHole = config.readNumEntry("Current Hole", 1);

		players.clear();
		KolfGame::scoresFromSaved(&config, players);
	}

	for (PlayerList::Iterator it = players.begin(); it != players.end(); ++it)
		scoreboard->newPlayer((*it).name());

	delete spacer;
	spacer = 0;
	delete game;
	game = new KolfGame(obj, &players, filename, dummy);
	game->setStrict(competition);

	connect(game, SIGNAL(newHole(int)), scoreboard, SLOT(newHole(int)));
	connect(game, SIGNAL(scoreChanged(int, int, int)), scoreboard, SLOT(setScore(int, int, int)));
	connect(game, SIGNAL(parChanged(int, int)), scoreboard, SLOT(parChanged(int, int)));
	connect(game, SIGNAL(modifiedChanged(bool)), this, SLOT(updateModified(bool)));
	connect(game, SIGNAL(newPlayersTurn(Player *)), this, SLOT(newPlayersTurn(Player *)));
	connect(game, SIGNAL(holesDone()), this, SLOT(gameOver()));
	connect(game, SIGNAL(checkEditing()), this, SLOT(checkEditing()));
	connect(game, SIGNAL(editingStarted()), this, SLOT(editingStarted()));
	connect(game, SIGNAL(editingEnded()), this, SLOT(editingEnded()));
	connect(game, SIGNAL(inPlayStart()), this, SLOT(inPlayStart()));
	connect(game, SIGNAL(inPlayEnd()), this, SLOT(inPlayEnd()));
	connect(game, SIGNAL(maxStrokesReached(const QString &)), this, SLOT(maxStrokesReached(const QString &)));
	connect(game, SIGNAL(largestHole(int)), this, SLOT(updateHoleMenu(int)));
	connect(game, SIGNAL(titleChanged(const QString &)), this, SLOT(titleChanged(const QString &)));
	connect(game, SIGNAL(newStatusText(const QString &)), this, SLOT(newStatusText(const QString &)));
	connect(game, SIGNAL(currentHole(int)), this, SLOT(setCurrentHole(int)));
	connect(holeAction, SIGNAL(activated(const QString &)), game, SLOT(switchHole(const QString &)));
	connect(nextAction, SIGNAL(activated()), game, SLOT(nextHole()));
	connect(prevAction, SIGNAL(activated()), game, SLOT(prevHole()));
	connect(firstAction, SIGNAL(activated()), game, SLOT(firstHole()));
	connect(lastAction, SIGNAL(activated()), game, SLOT(lastHole()));
	connect(randAction, SIGNAL(activated()), game, SLOT(randHole()));
	connect(editingAction, SIGNAL(activated()), game, SLOT(toggleEditMode()));
	connect(newHoleAction, SIGNAL(activated()), game, SLOT(addNewHole()));
	connect(clearHoleAction, SIGNAL(activated()), game, SLOT(clearHole()));
	connect(resetHoleAction, SIGNAL(activated()), game, SLOT(resetHole()));
	connect(undoShotAction, SIGNAL(activated()), game, SLOT(undoShot()));
	//connect(replayShotAction, SIGNAL(activated()), game, SLOT(replay()));
	connect(aboutAction, SIGNAL(activated()), game, SLOT(showInfoDlg()));
	connect(useMouseAction, SIGNAL(toggled(bool)), game, SLOT(setUseMouse(bool)));
	connect(useAdvancedPuttingAction, SIGNAL(toggled(bool)), game, SLOT(setUseAdvancedPutting(bool)));
	connect(soundAction, SIGNAL(toggled(bool)), game, SLOT(setSound(bool)));
	connect(showGuideLineAction, SIGNAL(toggled(bool)), game, SLOT(setShowGuideLine(bool)));
	connect(showInfoAction, SIGNAL(toggled(bool)), game, SLOT(setShowInfo(bool)));

	game->setUseMouse(useMouseAction->isChecked());
	game->setUseAdvancedPutting(useAdvancedPuttingAction->isChecked());
	game->setShowInfo(showInfoAction->isChecked());
	game->setShowGuideLine(showGuideLineAction->isChecked());
	game->setSound(soundAction->isChecked());

	layout->addWidget(game, 0, 0, AlignCenter);

	game->show();
	game->setFocus();

	setEditingEnabled(true);
	endAction->setEnabled(true);
	setHoleMovementEnabled(true);
	setHoleOtherEnabled(true);
	aboutAction->setEnabled(true);
	highScoreAction->setEnabled(true);
	printAction->setEnabled(true);
	saveAction->setEnabled(true);
	saveAsAction->setEnabled(true);
	saveGameAction->setEnabled(true);
	saveGameAsAction->setEnabled(true);

	clearHoleAction->setEnabled(false);
	newHoleAction->setEnabled(false);
	newAction->setEnabled(false);
	loadGameAction->setEnabled(false);
	tutorialAction->setEnabled(false);


	// so game can do stuff that needs to be done
	// after things above are connected
	game->startFirstHole(firstHole);

	end:
	delete dialog;
}