Пример #1
0
void gameController::update()
{
    
    m_oMouseLocScreen.update();
    m_oMouseLocWorld.loc.x = m_oMouseLocScreen.loc.x + m_pCamera.loc.x - CAM_OFFSET_X;
    m_oMouseLocWorld.loc.y = m_oMouseLocScreen.loc.y + m_pCamera.loc.y - CAM_OFFSET_Y;
    

    
    if ( m_bEditMode )
    {
        updateEdit();
    }else{
        updateGame();
    }
}
Пример #2
0
TGame::TGame(QObject *parent) :
    QObject(parent)
{

    game = new Game();

    TableView* table = game->getGameView();

    frame = new TFrame(table, game);
    frame->show();
    frame->updateFrame();
    QTimer *timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(updateGame()));
    timer->start(1000);
//    this->updateGame();
}
Пример #3
0
void Game::insertStone(const char *index){
    if(!posunuto) {
        posunuto = plan.posun(index, hrac, pocetHracu);
        string vPolicko = plan.vlozene_policko();
        if(posunuto == false) {
            cout << "Nelze vsunout policko na tohle misto" << endl;
        }
        else {
            hrac_posunul = true;
            can_move = true;
            scene->clear();
            updateGame();
            historie.push(index);
            historie.push(vPolicko);
        }
    }
}
Пример #4
0
void Game::Go()
{
    Event evt;

    while(pWnd->isOpen())
    {

        while (pWnd->pollEvent(evt))
        {
            processEvent(evt);
        }

        pWnd->clear();
        updateGame();
        drawGame();
        pWnd->display();
    }
}
Пример #5
0
void Pong::render()
{
	// we update the game state so things move.
	updateGame();

	// First we clear the screen
	
	glViewport(0, 0, Gdx.graphics->getWidth(), Gdx.graphics->getHeight());
	glClear(GL_COLOR_BUFFER_BIT);

	// Next we update the camera and set the camera matrix
	camera->update();
	camera->apply();

	// Now we render the ball, we remember that we
	// Defined 4 vertices so we use a triangle fan
	// We also push and pop the matrix. This is not really
	// necessary as the model view matrix doesn't contain
	// anything at this point.
	glPushMatrix();
	glTranslatef(ball.x, ball.y, 0);
	ballMesh->render(GL_TRIANGLE_FAN);
	glPopMatrix();

	// Rendering the two paddles works analogous
	glPushMatrix();
	glTranslatef(leftPaddle.x, leftPaddle.y, 0);
	paddleMesh->render(GL_TRIANGLE_FAN);
	glPopMatrix();

	glPushMatrix();
	glTranslatef(rightPaddle.x, rightPaddle.y, 0);
	paddleMesh->render(GL_TRIANGLE_FAN);
	glPopMatrix();

	// Finally we render the text centered at the top
	// of the screen. We use the text bounds for this.
	// For text to be transparent we have to enable blending and texturing.
	// We could setup blending once but i'm lazy :)
	spriteBatch->begin();
	// spriteBatch.drawText(font, score, Gdx.graphics.getWidth() / 2 - font.getStringWidth(score) / 2, Gdx.graphics.getHeight()
	// - font.getLineHeight(), Color.WHITE);
	spriteBatch->end();
}
Пример #6
0
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message,
                                 WPARAM wParam, LPARAM lParam)
{
    /**   process system messages   **/
    switch (message)
    {
        // when window is first created
        case WM_CREATE:
            // start timer running
            // with an ID of ID_TIMER (macro)
            // 20 millisecond intervals
            // and no callback function (thus we'll get a message instead)
            SetTimer(hwnd, ID_TIMER, 10, 0);
            break;
        // message from timer "ID_TIMER"
        case WM_TIMER:
            setUpdateRegion(hwnd); // add rectangle to update region
            updateGame(hwnd);     // do the game math update all rectangles
            UpdateWindow(hwnd);  // send WM_PAINT if update region is not empty
            break;
        // whenever the mouse moves over our window
        case WM_MOUSEMOVE:
            // store mouse position
            mpoint_x = MAKEPOINTS(lParam);
            // update paddle rectangle immediately
            updatePaddle();
            break;
        // sent when window is being closed
        case WM_DESTROY:
            cleanUp();
            PostQuitMessage(0);    // send a WM_QUIT a 0 to the message queue
            break;
        // the system message to paint the update region
        case WM_PAINT:
            // paint all rectangles to update region
            refreshWindow(hwnd);
            break;
        // for messages that we don't deal with use the default window procedure
        default:
            return DefWindowProc(hwnd, message, wParam, lParam);
    }

    return 0;
}
Пример #7
0
int main (int argc, char **argv) {
	int coinsTaken = 0;
	int gameOver = NO;
	
	printf("\n**** NIM - SPIEL ****\n");
	srand(time(NULL));
	numOfCoins = (rand() % 15) + 10;
	
	while (!gameOver) {
		printf("Auf dem Tischen liegen %d Münzen\n", numOfCoins);
		gameOver = updateGame();
	}
	
	if (humanMove) {
		printf("!!!!!! SIE HABEN GEWONNEN! !!!!!!\n");	
	} else {
		printf("** DER COMPUTER HAT GEWONNEN **\n");	
	}
	return 0;
}
Пример #8
0
void GameEngine::update(sf::Time &elapsedTime)
{
	handleEvents(elapsedTime);

	switch (data.state)
	{
	case CLOSING:
		return;

	case MAIN_MENU:
		updateMainMenu(elapsedTime);
		break;

	case RUNNING:
		updateGame(elapsedTime);
		break;

	default:
		break;
	}
}
Пример #9
0
int main(int argc, char** argv) {

	if (initialize()) {
		while (running) {
			beginFrame();

			updateInput();

			updateGame();

			updateRender();

			endFrame();
		} 
		end();
	}
	else
		Logger::log("CRITICAL ERROR: Could not initialize.");

	return 0;
}
Пример #10
0
	void ZombieGame::draw(Uint32 deltaTime) {
		gui::Component::draw(deltaTime);

		++frame_;
		lastFramTime_ += deltaTime;
		if (frame_ == 60) {
			meanFrameTime_ = lastFramTime_/1000.f;
			frame_ = 0;
			lastFramTime_ = 0;
		}
		
		viewPosition_ += 10 * deltaTime/1000.f * (refViewPosition_ - viewPosition_);
		
		if (started_) {
			updateGame(deltaTime / 1000.f);
		}

		drawGame(deltaTime / 1000.f);
				
		refViewPosition_ = humanState_.position_ + 0.5 * humanState_.velocity_;
	}
Пример #11
0
int main() {
    window = new sf::RenderWindow(sf::VideoMode(RES_X, RES_Y), "I love this Game");

    sf::Clock clock;
    float frameTime = 1/60.0f;
    float dTime = 0;

    initialiseGame();

    while (window->isOpen()) {
        dTime += clock.getElapsedTime().asSeconds();
        clock.restart();

        // Event handling
        sf::Event event;
        while(window->pollEvent(event)) {
            processEvent(event);
        }

        // Safeguard (slowdown) to prevent game from lagging to death
        if (dTime > 5*frameTime) dTime = 5*frameTime;

        // Update game
        while (dTime > frameTime) {
            dTime -= frameTime;
            updateGame();
        }

        // Draw frame
        window->clear();
        drawGameFrame();
        window->display();
    }

    delete window;
    return 0;
}
Пример #12
0
GameGui::GameGui(Game* game, QWidget* parent)
    : QWidget(parent)
{
    setWindowTitle(tr("Pong"));
    this->game = game;

    QHBoxLayout* pointsLayout = new QHBoxLayout();
    points1 = new QLCDNumber();
    points2 = new QLCDNumber();
    pointsLayout->addWidget(points1);
    pointsLayout->addStretch();
    pointsLayout->addWidget(points2);

    QGridLayout* tableLayout = new QGridLayout();
    tableLayout->setSpacing(0);
    tableLayout->setSizeConstraint(QLayout::SetFixedSize);
    for (int y = 0; y < game->getHeight(); ++y) {
        for (int x = 0; x < game->getWidth(); ++x) {
            QLabel* l = new QLabel();
            l->setFixedSize(20, 20);
            tableLayout->addWidget(l, y, x);
            labels.push_back(l);
        }
    }
    updateAllLabels();

    QVBoxLayout* allLayout = new QVBoxLayout();
    allLayout->addLayout(pointsLayout);
    allLayout->addLayout(tableLayout);
    this->setLayout(allLayout);
    adjustSize();

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateGame()));
    timer->start(100);
    show();
}
Пример #13
0
void Game::startGame(int size, int players){
    if(pocetHracu == 0 && velikost == 0) {
        pocetHracu = players_cbox->currentText().toInt();
        velikost = size_cbox->currentText().toInt();
    }
    switch(velikost) {
        case 5:
            labels_num = 2;
            break;
        case 7:
            labels_num = 3;
            break;
        case 9:
            labels_num = 4;
            break;
        case 11:
            labels_num = 5;
            break;
    }

    scene->clear();
    running = true;
    //vylosovani zacinajiciho hrace
    hracNaTahu = rand() % pocetHracu;
    posunuto = false;
    int pocetPredmetu = POCET_PREDMETU;
    if(velikost == 5) pocetPredmetu = 12;
    plan.inicializace(velikost,pocetPredmetu,pocetPredmetu/pocetHracu);
    plan.je_gui();
    hrac = new Hrac[pocetHracu];
    for(int i = 0; i < pocetHracu; i++){
        hrac[i] = Hrac(i, velikost);
        plan.prirad_predmet(&hrac[i]);
    }
    updateGame();
    show();
}
Пример #14
0
void Game::showInGameMenu(){
    menu = true;
    int n = scene->items().size();
    for(int i = 0; i < n; i++) {
        scene->items()[i]->setEnabled(false);
    }
    drawPanel(0, 0, 1024, 768, QColor(Qt::lightGray), 0.65);
    drawPanel(1024/2 - 200,200,400,400,QColor(Qt::darkGray), 0.85);

    Button *resume_btn = new Button(QString("Vratit do hry"));
    int x = scene->width()/2 - resume_btn->boundingRect().width()/2;
    int y = 250;
    resume_btn->setPos(x, y);
    connect(resume_btn, SIGNAL(clicked()), this, SLOT(updateGame()));
    scene->addItem(resume_btn);

    Button *save_game_btn = new Button(QString("Ulozit hru"));
    x = scene->width()/2 - save_game_btn->boundingRect().width()/2;
    y += 75;
    save_game_btn->setPos(x, y);
    //connect(save_game_btn, SIGNAL(clicked()), this, SLOT(showMainMenu()));
    scene->addItem(save_game_btn);

    Button *back_to_menu_btn = new Button(QString("Vratit do menu"));
    x = scene->width()/2 - back_to_menu_btn->boundingRect().width()/2;
    y += 75;
    back_to_menu_btn->setPos(x, y);
    connect(back_to_menu_btn, SIGNAL(clicked()), this, SLOT(showMainMenu()));
    scene->addItem(back_to_menu_btn);

    Button *exit_btn = new Button(QString("Konec"));
    x = scene->width()/2 - exit_btn->boundingRect().width()/2;
    y += 75;
    exit_btn->setPos(x, y);
    connect(exit_btn, SIGNAL(clicked()), this, SLOT(close()));
    scene->addItem(exit_btn);
}
Пример #15
0
int CALLBACK WinMain(
					HINSTANCE hInstance1,
					HINSTANCE hPrevInstance,
					LPSTR     lpCmdLine,
					int       nCmdShow
					)
{
	windowWidth = 800;
	windowHeight = 600;
	camZoom = 2;
	hInstance = hInstance1;
	LPCTSTR className = "GraphicsGame";
	WNDCLASS wc = {};
	wc.style = CS_OWNDC|CS_VREDRAW|CS_HREDRAW;
	wc.lpfnWndProc = (WNDPROC)WindowProc;
	wc.hInstance = hInstance;
	wc.lpszClassName = className;
	wc.hCursor = NULL;

	if(!RegisterClass(&wc))
	{
		killWindow(className);
		MessageBox(NULL, "Couldnt Register Class", "Error", MB_OK);
		return 1;
	}

	int windowStatus = createGLWindow(hInstance, className);
	if(!windowStatus)
	{
		return 1;
	}

	

	double dx = 0;
	double dy = 0;
	double maxSpeed = 5;
	double accel = 0.1f;
	MSG message;
	game = (Game*)calloc(1, sizeof(Game));
	initGL();
	initGame(game);
	int counter = 0;
	LARGE_INTEGER cps;
	LARGE_INTEGER curCount;
	LARGE_INTEGER prevCount;
	LONGLONG countDifference;

	QueryPerformanceFrequency(&cps);
	double secsPassed = 0;
	QueryPerformanceCounter(&curCount);
	float pan = 0.2;
	float topPan = 1;
	float lowPan = 0.2;
	while(!game->done)
	{
		prevCount = curCount;
		QueryPerformanceCounter(&curCount);
		countDifference = curCount.QuadPart - prevCount.QuadPart;
		secsPassed = (long double)countDifference / (long double)cps.QuadPart;
		while(PeekMessage(&message, hWindow, 0, 0, PM_REMOVE))
		{
			if(message.message == WM_QUIT)
			{
				game->done = true;
			}
			TranslateMessage(&message);
			DispatchMessage(&message);
		}
		dx = 0;
		dy = 0;
		if(game->keys[VK_SHIFT])
		{
			pan = topPan;
		}
		else
		{
			pan = lowPan;
		}
		if(game->keys['W'])
		{
			camY+=pan;
		}
		if(game->keys['A'])
		{
			camX-=pan;
		}
		if(game->keys['S'])
		{
			camY-=pan;
		}
		if(game->keys['D'])
		{
			camX+=pan;
		}
		
		if(game->keys['Q'])
		{
			camZoom += 0.01;
			if(camZoom > 6) camZoom = 6;
			resize(windowWidth, windowHeight);
		}
		if(game->keys['E'])
		{
			camZoom -= 0.01;
			if(camZoom < 1) camZoom = 1;
			resize(windowWidth, windowHeight);
		}
		if(game->keys[VK_SPACE])
		{
			saveFile(game);
			
		}
		
		
		



		updateGame(game, dx, dy, secsPassed);
		
		drawScene(game);
		SwapBuffers(hDeviceContext);

	}
	free(game);
	killWindow(className);
	return 0;
}
Пример #16
0
void Framework::loop()
{
	/* main loop variable */
	bool done = false;
	/* used to collect events */
	SDL_Event event;

	/* wait for events */
	while (!done)
	{
		/* handle the events in the queue */
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_MOUSEMOTION:
				/* give away mouse movement with buttons pressed */
				handleMouseMove(event.motion.xrel, event.motion.yrel, event.motion.state);
				break;
			case SDL_MOUSEBUTTONUP:
				/* handle mouse button release for serving */
				if (event.button.button == SDL_BUTTON_LEFT)
					if (!paused) serveBall();
			case SDL_KEYDOWN:
				/* handle key presses */
				handleKeyPress(&event.key.keysym);
				break;
			case SDL_QUIT:
				/* handle quit requests */
				done = true;
				break;
			case SDL_USEREVENT:
				switch (event.user.code)
				{
				case NET2_EXTERNAL:
					if (((TimerData*)event.user.data1)->timer == NULL)
					{
						/* this means our timer has gone inactive and we are pleased to stop our work! */
					} else {
						((TimerData*)event.user.data1)->receiver->action(((TimerData*)event.user.data1)->event);
					}
					break;
				case NET2_ERROREVENT:
					printf("Error: %s(%d)\n", NET2_GetEventError(&event), NET2_GetSocket(&event));
					break;
				case NET2_UDPRECEIVEEVENT:
					UDPpacket *p = NULL;
					p = NET2_UDPRead(NET2_GetSocket(&event));
					while (p != NULL) // if we get NULL we are done
					{
						Peer* peer = getCreatePeer(p->address.host);
						receivePacket(peer, (char*)p->data, p->len);
						NET2_UDPFreePacket(p);
						p = NET2_UDPRead(NET2_GetSocket(&event));
					}
					break;
				}
			}
		}

		int tdiff = SDL_GetTicks() - lasttime;
		if (tdiff > timeunit) {
			frames++;
			xdiff += tdiff; // always greater 0 because we decided to let tdiff be greater than timeunit
			if ((xdiff >= 100)&&(xdiff >= timeunit * 20)) {
				output.updateFPS(frames * 1000.0 / xdiff); // There are 1000 ticks / second
				frames = 0;
				xdiff = 0;
			}
			lasttime += tdiff;

			// Game status code
			updateGame(tdiff);

			// Rendering code
			drawScene();
		}
	}
}
Пример #17
0
int main()
{
	ALLEGRO_DISPLAY* display = NULL;
	ALLEGRO_DISPLAY_MODE disp;
	ALLEGRO_EVENT_QUEUE* eq = NULL;

	ALLEGRO_TIMER* timer = NULL;
	ALLEGRO_TIMER* ball_timer = NULL;

	bool run = true;
	bool draw = false;

	if (!al_init())
	{
		return -1;
	}

	al_get_display_mode(al_get_num_display_modes() - 1, &disp);

	std::cout << disp.height << " " << height << std::endl;
	std::cout << disp.width << " " << width << std::endl;

	height = disp.height / 3 * 2;
	width = height / 9 * 16;

	std::cout << disp.height << " " << height << std::endl;
	std::cout << disp.width << " " << width << std::endl;

	al_set_new_display_flags(ALLEGRO_FULLSCREEN);
	display = al_create_display(width, height);
	al_set_window_title(display, "PONG V2");

	if (display == NULL)
	{
		return -1;
	}

	init(&player1, &player2, &ball);

	eq = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);
	ball_timer = al_create_timer(15.0);

	al_install_keyboard();
	al_init_primitives_addon();
	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("./arial.ttf", 18, 0);
	scorefont = al_load_ttf_font("./arial.ttf", (height * width) / 36000, 0);

	al_register_event_source(eq, al_get_keyboard_event_source());
	al_register_event_source(eq, al_get_display_event_source(display));
	al_register_event_source(eq, al_get_timer_event_source(timer));

	al_hide_mouse_cursor(display);
	al_start_timer(timer);

	while (run)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(eq, &ev);
		if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			draw = true;
		}
		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			run = false;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
				case ALLEGRO_KEY_S:
					keys[P1][DOWN] = true;
					break;
				case ALLEGRO_KEY_W:
					keys[P1][UP] = true;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[P2][DOWN] = true;
					break;
				case ALLEGRO_KEY_UP:
					keys[P2][UP] = true;
					break;
				case ALLEGRO_KEY_SPACE:
					start = true;
					firstGame = false;
					break;
				case ALLEGRO_KEY_ESCAPE:
					run = false;
					break;
				case ALLEGRO_KEY_P:
					if (pause == true) pause = false;
					else if (pause == false) pause = true;
					break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
				case ALLEGRO_KEY_S:
					keys[P1][DOWN] = false;
					break;
				case ALLEGRO_KEY_W:
					keys[P1][UP] = false;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[P2][DOWN] = false;
					break;
				case ALLEGRO_KEY_UP:
					keys[P2][UP] = false;
					break;
			}
		}
		if (draw && al_event_queue_is_empty(eq))
		{
			if (!pause)
			{
				if (keys[P1][UP])update(&player1, -1);
				if (keys[P1][DOWN])update(&player1, 1);
				if (keys[P2][UP])update(&player2, -1);
				if (keys[P2][DOWN])update(&player2, 1);

				update(&ball);
				updateGame(&player1, &player2, &ball);
				render();
				draw = false;
			}
		}
	}

	al_destroy_display(display);
	al_destroy_event_queue(eq);

	return 0;
}
//controll the program navigation
void Soccer_league::start(string str)
{

	while(!str.substr(0,1).compare(" "))
		str=str.substr(1,str.length());

	if (str.length()<1)return;
	//if there is a user file to read and he inserted before lunce the program


	//getting the next action/request fron the user
inputerror: //getline(cin,str);
	//real input because i change it to lower case and without spaces
	string realInput = str;
	/*all the matches will be without spaces and with lower case*/
	str.erase( std::remove(str.begin(),str.end(),' '), str.end() );
	std::transform(str.begin(), str.end(), str.begin(), ::tolower);

	//check if str starts with '.' it should be a regex
	if (str.substr(0,1).compare(".")==0||str.substr(0,1).compare(",")==0||str.substr(0,1).compare("/")==0)
	{
		goto inputerror;
	}
	if (str.compare("help")==0)
	{

	}
	// statments
	if (str.compare("showleague")==0)
	{
		printLeagueTabel(_team);
	}
	//display the team names
	else if (str.compare("showteams")==0)
	{
		cout<<"Team Name"<<endl;
		cout<<"-----------"<<endl;
		for (int i=0 ; i< _team.size();i++)
		{
			cout<<_team[i]->get_teamName()<<endl;
		}

	}
	//display a specific game
	else if (str.substr(0,4).compare("show")==0 && (str.length()-4)>=2 && realInput.substr(0,5).compare("show ")==0 && realInput.substr(0,5).compare("Show ")==0)
	{
		//split the string into 2 parts each one of then is a team name
		str = str.substr(4,str.length());
		int locationInLine=0;
		string splited,home,guest;
		for (int i=0 ; i < realInput.length(); i++)
		{
			string temp = realInput.substr(i,1);
			if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
			{
				home=splited;
				locationInLine+=i+3;
				guest=realInput.substr(locationInLine,realInput.length());
				splited.clear();
				break;
			}
			splited.append(temp);
		}
		home = home.substr(5,home.length()-1);
		//search the requested game in reverse order to get the latest game
		for (int i=_game.size()-1; i >= 0 ; i--)
		{
			if (home.compare(_game[i]->get_home())==0 && guest.compare(_game[i]->get_guest().substr(0,(_game[i]->get_guest().length())))==0)
			{
				cout<<getGameDetails(i,_game)<<endl;
				break;
			}
		}
	}



	//check if we have date elements like . , / and it start with game namber
	else if (str.find("game")!= std::string::npos&&(str.find(".")!= std::string::npos || str.find(",")!= std::string::npos || str.find("/")!= std::string::npos))
	{
		//delete the word 'game' from the input string and keep only the number
		int gameNumber=0;
		if(str.substr(5,6).compare(",") || str.substr(5,6).compare("."))
			gameNumber = atoi(str.substr(4,5).c_str());
		string strGame=str.substr(6,str.length());
		//finally check if the input is date
		Date* date = (checkDate(strGame));
		for (int i=0; i< _game.size(); i++)
		{
			Date* d = _game[i]->get_date();
			if (*d==*date && _game[i]->get_round() == gameNumber)
			{
				//display the asks games
				cout<<getGameDetails(i,_game)<<endl;
			}
		}
		cout<<endl;
	}

	//access allow only if you are the manager
	if (str.substr(0,5).compare("admin")==0)
	{
		//remove the admin word from the beginning and keep the left string
		string strAdmin = str.substr(5,str.length());

		if (strAdmin.substr(0,7).compare("addgame")==0)
		{
			//close the ream registeration
			if(_isOpen==1 )
			{
				_dateBase->get_file()<<("START")<<endl;
				_dateBase->get_file()<<("END")<<endl;
				_isOpen=0;
			}

			int location= realInput.find("game");
			string newGame = realInput.substr(location+4,realInput.length());
			//check if the game is correct by names and game number and act.
			addGame(newGame,_dateBase->get_file(),_game);
			//_game.push_back(new Game(newGame));
			//writeToFileinTheEnd(newGame);
			interpretGamesToTeamsStatus(_team,_game.at(_game.size()-1));
			string output = "user add a new game ";
			output+=newGame;
			writeToOUTPUTfile(output,_dateBase->get_output());
		}
		//register teams
		if (strAdmin.substr(0,13).compare("registerteams")==0)
		{

			if(_isOpen==1)
			{
				string newTeam;int check=1;
				vector<string> vec;
				//save my list in vector to comper with the input string
				for (int i=0;i<_team.size();i++)
				{
					vec.push_back(_team[i]->get_teamName());
				}
				//cout<<"insert team names: "<<endl;
				//check is the inset team is not exist and exit when ; insert
				while (!newTeam.compare(";")==0)
				{

					getline (cin,newTeam);
					for (int i=0;i<vec.size();i++)
					{
						if(newTeam.compare(vec[i])==0)
						{
							cout<<"team "<<newTeam<< " is already registered"<<endl;
							check=0;
						}
					}
					if (check==1 && !newTeam.compare(";")==0)
					{
						writeToFileinTheEnd(newTeam,_dateBase->get_file());
						string output = "user add a new team ";
						output+=newTeam;
						writeToOUTPUTfile(output,_dateBase->get_output());
						_team.push_back(new Team(newTeam));
					}
					check=1;
				}
				cout<< "Teams was added"<<endl;
			}
			else
			{
				cout<<"cannot add new teams because the league is already started"<<endl;
			}
		}
		//update team name
		if (strAdmin.substr(0,17).compare("correctionreplace")==0)
		{
			int location = realInput.find("replace");
			realInput = realInput.substr(location+8,realInput.length());
			//seperate the old team name and new team name
			int locationInLine=0;
			string splited,oldTeam,newTeam;
			string temp = realInput;
			oldTeam = temp.substr(0,realInput.find("by")-1);
			newTeam = temp.substr(realInput.find("by ")+3,temp.length());

			/*for (int i=0 ; i < realInput.length(); i++)
			{
			string temp = realInput.substr(i,1);
			if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
			{
			oldTeam=splited;
			locationInLine+=i+3;
			newTeam=realInput.substr(locationInLine,realInput.length());
			splited.clear();
			break;
			}
			splited.append(temp);
			}*/

			//update team name into the data base
			replace_line_in_file(oldTeam , newTeam, _dateBase->get_file(), _team , _game);
			string output = "user replace team name ";
			output+= oldTeam;
			output+=" to ";
			output+=newTeam;
			writeToOUTPUTfile(output,_dateBase->get_output());
			//cout<< "Team name updated"<<endl;
		}
		if (strAdmin.substr(0,14).compare("correctiongame")==0)
		{
			strAdmin = strAdmin.substr(strAdmin.find("game")+4,strAdmin.length());
			string gameNumber = strAdmin.substr(0,1);
			string sdate = strAdmin.substr(2,strAdmin.length());
			Date* date = checkDate(strAdmin.substr(2,strAdmin.length()));
			updateGame(gameNumber, sdate,_dateBase->get_file(),_team,_game);
		}
		if (strAdmin.substr(0,16).compare("correctiondelete")==0)
		{
			if(_isOpen)
			{
				int location = realInput.find("delete");
				string teamToRemove = realInput.substr(location+7,realInput.length());
				removeLine(teamToRemove,_dateBase->get_file());
				for (int i=0; i<_team.size();i++)
				{
					if (_team[i]->get_teamName().compare(teamToRemove)==0)
					{
						_team.erase(_team.begin()+i);
						string output = "user delete team ";
						output+= teamToRemove;
						writeToOUTPUTfile(output,_dateBase->get_output());
						break;
					}
				}
			}
			else cout<<"cannot delete team because the league is already started"<<endl;

		}
		if (strAdmin.substr(0,10).compare("correction")==0 && strAdmin.find('-') != std::string::npos )
		{
			realInput = realInput.substr(realInput.find("correction")+11,realInput.length());
			int locationInLine=0;
			string splited,home,guest;
			string temp = realInput;
			for (int i=0 ; i < realInput.length(); i++)
			{
				string temp = realInput.substr(i,1);
				if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
				{
					home=splited;
					locationInLine+=i+3;
					guest=realInput.substr(locationInLine,realInput.length());
					splited.clear();
					break;
				}
				splited.append(temp);
			}
			string score;
			for (int i=0 ; i < guest.length(); i++)
			{
				string temp = guest.substr(i,1);
				try{
					if (guest.length()>(i+4) && atoi(temp.c_str())>0)
					{
						score = guest;
						guest=splited.substr(0,splited.length()-1);
						locationInLine+=i;
						score=score.substr(guest.length()+1,score.length());
						splited.clear();
						break;
					}
				}
				catch(exception e){};
				splited.append(temp);
			}
			updateGameDetails(home,guest,score,_dateBase->get_file(),_team,_game);
			interpretGamesToTeamsStatus(_team,_game.at(_game.size()-1));

		}
	}
	if (str.compare("exit")==0)
	{
		_dateBase->get_file().close();
		return;
	}

}
Пример #19
0
void main()
	{
	menu();
	while(true){
	sf::Clock clock, clockInvincible;
    score1 = 0;
	int  xBlock, yBlock, x, y, seconds = 0, red, green, blue;
	int direction = 0, directionOfBack = 0, size;
	bool checkGameOver = false, outOfBounds = false, restarter = false, breaker = false;
			size = Robjects.size();
			Robjects.erase(Robjects.begin()+0, Robjects.begin()+size);
			window.clear();
	//---------------------------------------------------------------------------
	//sf::RenderWindow window(sf::VideoMode(600, 500), "Testing");
	//---------------------------------------------------------------------------
	event.type = sf::Event::Count;
	sf::RectangleShape square(sf::Vector2f(sizex, sizey));
	square.setFillColor(sf::Color(200, 60, 0));
	square.setOutlineThickness(2);
    square.setOutlineColor(sf::Color(140, 30, 0));
	//---------------------------------------------------------------------------
	sf::RectangleShape egg(sf::Vector2f(sizex + 2, sizey + 2));
	egg.setFillColor(sf::Color(red, green, blue));
	egg.setOutlineThickness(2);
    egg.setOutlineColor(sf::Color(200, 200, 200));
	//---------------------------------------------------------------------------
	setAll(x, y, xBlock, yBlock);
	//---------------------------------------------------------------------------
  	egg.setPosition(xBlock, yBlock);
	//---------------------------------------------------------------------------
	setEgg(red, green, blue);
 while(window.isOpen())
	  {
		  if(invincible1 == true){
			  invincible2(x, y);
		for(int i = 0; i < Robjects.size(); i++){
	Robjects[i].setFillColor(sf::Color(200, 50, 50));
	Robjects[i].setOutlineThickness(2);
    Robjects[i].setOutlineColor(sf::Color(40, 40, 40));
		}
		  }
		  else 
              outOfBounds = checkOutOfBounds(x , y);

	sf::Time elapsed1 = clock.getElapsedTime();
	seconds = elapsed1.asMilliseconds();
	//---------------------------------------------------------------------------
    restarter = updateGame(x, y, xBlock, yBlock, direction, directionOfBack, checkGameOver, seconds, red, green, blue);

	egg.setFillColor(sf::Color(red, green, blue));
	if(restarter == true)
	clock.restart();
	directionOfBack = CreateTail(x, y, direction, checkGameOver, false);
   	//---------------------------------------------------------------------------
	if((x % 25 == 0)&&(y % 25 == 0)){
		//------------------------------------------------------------
		  while(window.pollEvent(event)) {
			  if(event.type == sf::Event::Closed){
			size = Robjects.size();
			Robjects.erase(Robjects.begin()+0, Robjects.begin()+size);
				  window.close();

			  }
			  //---------------------------------------------------------------------
			  if((event.key.code == sf::Keyboard::P)&&(event.type == sf::Event::KeyPressed)){
			  window.draw(square);
			  for(int i = 0; i < Robjects.size(); i++)
			  window.draw(Robjects[i]);

			  if(eggs == true){}
			  else
			  window.draw(egg);

			  window.draw(score);
		      window.display();
				  while(true){
			  while(window.pollEvent(event)) {
			  if((event.key.code == sf::Keyboard::P)&&(event.type == sf::Event::KeyPressed))
				  breaker = true;
			  			  }
			  if(breaker == true)
				  break;
			  }
			  }
				  breaker = false;
				  event.key.code == sf::Keyboard::Q;
			  if(event.type == sf::Event::KeyPressed){
			  direction = move(direction, x, y);
			  square.setPosition(x,y);
			  }
		    }
		  }
	//---------------------------------------------------------------------------
		if((checkGameOver == true)||(outOfBounds == true))
		{
			  window.clear();
		      window.draw(square);
			  for(int i = 0; i < Robjects.size(); i++)
			  window.draw(Robjects[i]);
			  window.draw(egg);
			  window.draw(score);
			  window.draw(gameOver);
              exit();
			  window.clear();
			  menu();
			  break;
		 }
	//---------------------------------------------------------------------------
		  square.setPosition(x,y);
		  egg.setPosition(xBlock, yBlock);

		  	  window.clear();
		      window.draw(square);
			  for(int i = 0; i < Robjects.size(); i++)
			  window.draw(Robjects[i]);

			  if(eggs == false){
				    window.draw(egg);
			  }
			  else{
		for(int i = 0; i < 120; i++)
		window.draw(egger[i]); 
			  }
			  			if(invincible == true)
	{
			invincible3.setString("I");
	        invincible3.setFont(font);
	        invincible3.setCharacterSize(10);
	        invincible3.setColor(sf::Color(255, 255, 255));
	        invincible3.setPosition(xBlock + 4, yBlock + 4);
			window.draw(invincible3);
	}
			  window.draw(score);
		      window.display();
			  if(eggs == true)
				  sf::sleep(sf::seconds(.0009));
			  else
			 sf::sleep(sf::seconds(.003));
	  }
}
    //return 0;
}
Пример #20
0
void Framework::loop()
{
	/* main loop variable */
	bool done = false;
	/* used to collect events */
	SDL_Event event;

	/* wait for events */
	while (!done)
	{
		/* handle the events in the queue */
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_MOUSEMOTION:
				/* give away mouse movement with buttons pressed */
				handleMouseMove(event.motion.xrel, event.motion.yrel, event.motion.state);
				break;
			case SDL_MOUSEBUTTONUP:
				/* handle mouse button release for serving */
				if (event.button.button == SDL_BUTTON_LEFT)
					if (!paused) serveBall();
			case SDL_KEYDOWN:
				/* handle key presses */
				handleKeyPress(&event.key.keysym);
				break;
			case SDL_QUIT:
				/* handle quit requests */
				done = true;
				break;
			case SDL_USEREVENT:
				if (((TimerData*)event.user.data1)->timer == NULL)
				{
					/* this means our timer has gone inactive and we are pleased to stop our work! */
				} else {
					((TimerData*)event.user.data1)->receiver->action(((TimerData*)event.user.data1)->event);
				}
				break;
			}
		}
		int tdiff = SDL_GetTicks() - lasttime;
		if (tdiff > timeunit) {
			frames++;
			xdiff += tdiff; // always greater 0 because we decided to let tdiff be greater than timeunit
			if ((xdiff >= 500)&&(xdiff >= timeunit * 25)) {
				output.updateFPS(frames * 1000.0 / xdiff); // There are 1000 ticks / second
				frames = 0;
				xdiff = 0;
				ping();
			}
			lasttime += tdiff;

			// Multiplayer code
			doNetworking();

			// Game status code
			updateGame(tdiff);

			// Rendering code
			drawScene();
		}
	}
}
Пример #21
0
int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE,
                     LPSTR,
                     int nCmdShow)
{
  HWND hwnd;               /* This is the handle for our window */
  WNDCLASSEX wincl;        /* Data structure for the windowclass */

  /* The Window structure */
  wincl.hInstance = hThisInstance;
  wincl.lpszClassName = szClassName;
  wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
  wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
  wincl.cbSize = sizeof (WNDCLASSEX);

  /* Use default icon and mouse-pointer */
  wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
  wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
  wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  wincl.lpszMenuName = NULL;                 /* No menu */
  wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
  wincl.cbWndExtra = 0;                      /* structure or the window instance */
  /* Use Windows's default colour as the background of the window */
  wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

  /* Register the window class, and if it fails quit the program */
  if (!RegisterClassEx (&wincl))
      return 0;

  int width = windowWidth + GetSystemMetrics(SM_CXFIXEDFRAME) * 2;
  int height = windowHeight + GetSystemMetrics(SM_CYFIXEDFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION);

  /* The class is registered, let's create the program*/
  hwnd = CreateWindowEx (
         0,                   /* Extended possibilites for variation */
         szClassName,         /* Classname */
         "IF, THEN",       /* Title Text */
         WS_CAPTION, /* default window */
         CW_USEDEFAULT,       /* Windows decides the position */
         CW_USEDEFAULT,       /* where the window ends up on the screen */
         width,                 /* The programs width */
         height,                 /* and height in pixels */
         HWND_DESKTOP,        /* The window is a child-window to desktop */
         NULL,                /* No menu */
         hThisInstance,       /* Program Instance handler */
         NULL                 /* No Window Creation data */
         );

  /* Make the window visible on the screen */
  ShowWindow (hwnd, SW_SHOW);

  /* Run the message loop. It will run until GetMessage() returns 0 */

  HDC hdc = GetDC(hwnd);

  hBufferDC = CreateCompatibleDC(hdc);
  hBufferBmp = CreateCompatibleBitmap(hdc, windowWidth, windowHeight);
  hOldBufferBmp = (HBITMAP)SelectObject(hBufferDC, hBufferBmp);

  DWORD lastTime = GetTickCount();

  NextLevel();

  while (!bGameOver)
  {
    MSG msg;
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
      if (msg.message == WM_QUIT)
        bGameOver = true;
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    if (bGameOver)
      break;

    if (GetAsyncKeyState(VK_ESCAPE))
      break;

    updateGame();
    PaintGame(hBufferDC);

    BitBlt(hdc, 0, 0, windowWidth, windowHeight, hBufferDC, 0, 0, SRCCOPY);

    do
      Sleep(0);
    while (GetTickCount() - lastTime < 15);

    lastTime = GetTickCount();
  }

  SelectObject(hBufferDC, hOldBufferBmp);
  DeleteObject(hBufferBmp);
  DeleteObject(hBufferDC);

  ReleaseDC(hwnd, hdc);

  /* The program return-value is 0 - The value that PostQuitMessage() gave */
  return 0;
}
Пример #22
0
int main()
#endif
{
	int quit = 0;
	int timer = 0;

	srand(time(NULL));
	Context context = FIRSTMENU;
	SDL_Event event;
	SDL_Window *window = NULL;
	SDL_Surface *windowSurface = NULL;
	SDL_Renderer *windowRenderer = NULL;
	Menu *menu = NULL;
	Game *game = NULL;
	
	/* Init the window or exit if failure. */
	if(!init(&window))
		return EXIT_FAILURE;

	/* Make the window renderer and the window surface */
	windowRenderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_TARGETTEXTURE);
	if(windowRenderer == NULL)
		printf("%s \n", SDL_GetError());

	windowSurface = SDL_GetWindowSurface(window);

	/* Make all context of the game. */
	menu = initMenu(windowRenderer);
	game = initGame(windowRenderer);

	while(!quit)
	{
		/* event loop. */
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				quit = 1;

			else if(event.type == SDL_KEYDOWN)
			{
				const Uint8* keyPressed = SDL_GetKeyboardState(NULL);
				if(context == GAME)
				{
					/* Handle the translation of the blocks */
					if(event.key.keysym.scancode == SDL_SCANCODE_LEFT || event.key.keysym.scancode == SDL_SCANCODE_RIGHT || event.key.keysym.scancode == SDL_SCANCODE_DOWN)
					{
						if(event.key.keysym.scancode == SDL_SCANCODE_LEFT)
							moveCurrentBlock(game, LEFT);
						if(event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
							moveCurrentBlock(game, RIGHT);
						if(event.key.keysym.scancode == SDL_SCANCODE_DOWN)
							moveCurrentBlock(game, DOWN);
					}

					/* Handle the rotation of the blocks */
					else if(event.key.keysym.sym == SDLK_w || event.key.keysym.sym == SDLK_x)
					{
						/* Check the direction the user want to move */
						Direction direction = NONE;
						if(keyPressed[SDL_SCANCODE_RIGHT])
							direction = RIGHT;
						else if(keyPressed[SDL_SCANCODE_LEFT])
							direction = LEFT;

						if(event.key.keysym.sym == SDLK_w)
						{
							rotateCurrentBlock(game, 1, direction);
						}
						else
							rotateCurrentBlock(game, -1, direction);
					}

					else if(event.key.keysym.scancode == SDL_SCANCODE_SPACE)
					{
						putDownCurrentBlock(game);
					}
				}
			}
		}

		SDL_RenderClear(windowRenderer);

		/* Call the correct context */
		if(context == FIRSTMENU)
			firstMenu(menu, windowRenderer, &context);
		else if(context == QUIT)
			quit = 1;
		else if(context == GAME)
			updateGame(game);

		SDL_RenderPresent(windowRenderer);
		fpsManager(&timer);
	}

	/* Clear the allocated memory */
	clearMenu(menu);
	clearGame(game);
	SDL_DestroyRenderer(windowRenderer);
	SDL_FreeSurface(windowSurface);
	SDL_DestroyWindow(window);
	clear();

	return 0;
}
Пример #23
0
void Game::keyReleaseEvent(QKeyEvent *event){
    if (event->key() == Qt::Key_Control) {
        updateGame();
    }
}