void EnemyBullet::update(sf::Time timeElapsed) { sprite.move(velocity * timeElapsed.asSeconds()); if (sprite.getPosition().y > GAME_HEIGHT) { enabled = false; } if (game->player1.enabled && isColliding(&game->player1)) { //enabled = false; //game->player1.enabled = false; game->player1.sprite.setPosition((GAME_WIDTH / 2), ((GAME_HEIGHT * 7) / 8)); } if (game->MULTI_PLAYER) { if (game->player2.enabled && isColliding(&game->player2)) { //enabled = false; //game->player2.enabled = false; game->player2.sprite.setPosition((GAME_WIDTH / 2), ((GAME_HEIGHT * 7) / 8)); } } }
int Update(App* app) { app->player.vel.y += 2; if (app->player.vel.y > PLAYER_TERMINAL_VELOCITY) app->player.vel.y = PLAYER_TERMINAL_VELOCITY; app->player.box.x += app->player.vel.x; app->player.box.y += app->player.vel.y; if(WColliding(&app->player.box)) app->player.vel.y = 0; for (int i = 0; i < app->ground.count; ++i) { if (isColliding(&app->player.box, &app->ground.box[i])) { app->player.jumping = 0; app->player.box.y = app->ground.box[i].y - PLAYER_HEIGHT; } } for (int i = 0; i < app->platform.count; ++i) { if (isColliding(&app->player.box, &app->platform.box[i])) { // TODO : action } } return 0; }
bool Tetramino::tryMove(Direction dir) { if (dir == TETRIS_DIR_UP) return false; int oldX = _offsetX; int oldY = _offsetY; if (dir == TETRIS_DIR_DOWN) _offsetY++; else if (dir == TETRIS_DIR_LEFT) _offsetX--; else _offsetX++; int size = _game->_tets.size(); int pos = _offsetY; if(isColliding()) { _offsetX = oldX; _offsetY = oldY; return false; } _game->updateGrid(); return true; }
void Enemy::AI(float x, float y) { //SDL_LockMutex(mutex); //Sem Lock SDL_SemWait(moveLock); //std::cout << "AI Lock" << std::endl; m_dirX = 0; m_dirY = 0; if (m_x < x) { m_dirX = 1; } else if (m_x > x) { m_dirX = -1; } if (m_y < y) { m_dirY = 1; } else if (m_y > y) { m_dirY = -1; } isColliding(x,y); //SDL_UnlockMutex(mutex); SDL_SemPost(moveLock); //std::cout << "AI Unlock" << std::endl; }
void Game::checkCollisions() { list<list<shared_ptr<Bullet> >::iterator> bulletsToRemove; list<list<shared_ptr<Enemy> >::iterator> enemiesToRemove; for (auto it = bullets.begin(); it != bullets.end(); ++it) { if ((*it)->getPosZ() > 0 || (*it)->getPosZ() < -this->getDepth()) bulletsToRemove.push_back(it); else { for (auto eIt = enemies.begin(); eIt != enemies.end(); ++eIt) { if (!(*it)->isHostile() && isColliding(*it, *eIt)) { bulletsToRemove.push_back(it); (*eIt)->damage((*it)->getDamage()); if ((*eIt)->getHealth() <= 0) enemiesToRemove.push_back(eIt); } } } } for (auto it : bulletsToRemove) bullets.erase(it); for (auto it : enemiesToRemove) enemies.erase(it); }
// Function to handle all sorts of things that happen inside this object every tick void BaseObject::update(std::vector<BaseObject> objects) { xpos += velX; ypos += velY; if (clsn != NULL) clsn->update(xpos, ypos); bool hitFloor = false; for (int i = 0; i < 2; i++) { if (&objects.at(i) != this) { if (objects.at(i).isSolid()) { if (isColliding(objects.at(i).getClsn())) { if (clsn->bottom >= objects.at(i).getClsn()->top) { hitFloor = true; velY = 0; } } } } } if (!hitFloor && gravity > 0) { velY += gravity; } update_animation(); // update sprite animation ticks for (unsigned int i = 0; i < elements.size(); i++) { elements.at(i)->run(); } }
void Castle::addRectangles() { srand(time(NULL)); for (int i = 0; i < m_settings.rect_number; i++) { RECT r = getRandomRect(); while (!isColliding(r)) r = getRandomRect(); m_rectangles.push_back(r); for (int j = r.left; j <= r.right; j++) { if (j == r.left || j == r.right) { m_matrix[j][r.top] = 'T'; m_matrix[j][r.bottom] = 'T'; } else { m_matrix[j][r.top] = 'W'; m_matrix[j][r.bottom] = 'W'; } } for (int k = r.top + 1; k <= r.bottom - 1; k++) { m_matrix[r.left][k] = 'W'; m_matrix[r.right][k] = 'W'; } } this->toString(); }
bool Robot::isColliding(Piece piece) { for (int i = 0; i < piece.size(); i++) if (isColliding(piece[i])) return true; return false; }
//Fills the provided vector with resultant points (points //contained in the specified range). Returns total results unsigned int queryRange(aabb& range, std::vector<T>& results) { //std::cout << bounds.x << " , " << bounds.y << " w " << bounds.w << " h " << bounds.h << " \n"; unsigned int totalResults = 0; //Make sure range is touching this node if (!isColliding(&range, &bounds)) { return 0; } //Add points in this node to results if contained in range for (typename std::list<QuadPoint<T> >::iterator it = data.begin(); it!=data.end(); ++it) { //std::cout << "has point\n"; if (isPointInRange((*it).x, (*it).y, range)) { results.push_back((*it).data); totalResults++; } } //Let all child nodes (if any) add points if (!tL) { return totalResults; } totalResults += tL->queryRange(range, results); totalResults += tR->queryRange(range, results); totalResults += bL->queryRange(range, results); totalResults += bR->queryRange(range, results); return totalResults; }
void BoxGroup::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Down : moveBy(0, 20); if (isColliding()) { moveBy(0, -20); // 将小方块从方块组中移除到场景中 clearBoxGroup(); // 需要显示新的方块 emit needNewBox(); } break; case Qt::Key_Left : moveBy(-20, 0); if (isColliding()) moveBy(20, 0); break; case Qt::Key_Right : moveBy(20, 0); if (isColliding()) moveBy(-20, 0); break; case Qt::Key_Up : rotate(90); if(isColliding()) rotate(-90); break; // 空格键实现坠落 case Qt::Key_Space : moveBy(0, 20); while (!isColliding()) { moveBy(0, 20); } moveBy(0, -20); clearBoxGroup(); emit needNewBox(); break; } }
bool CustomKinestheticTeacher::isDifferentialCommandSafe(arma::vec diffCommand,arma::vec currentJointStates){ bool okay=true; int checkTimesAhead=3; for (auto i = 1;i<=checkTimesAhead;i++) if (isColliding(armadilloToStdVec(i*diffCommand + currentJointStates))) okay=false; return okay; }
void idle() { glm::dvec3 colorFieldGradient; double colorFieldLaplacian; // Print OpenGL errors, if there are any (for debugging) if (GLenum err = glGetError()) { std::cerr << "OpenGL ERROR: " << gluErrorString(err) << std::endl; } static double previous_time; static bool initialized = false; if (!initialized) { previous_time = double(clock()) / CLOCKS_PER_SEC; initialized = true; } double current_time = double(clock()) / CLOCKS_PER_SEC; double elapsed_time = current_time - previous_time; double dt = timestep;// elapsed_time; //reset force and density if (running) updateParticles(particles, partCount, h, eta, dt, sphereRadius, threshold, sigma); //check each particle for collision for (int i = 0; i < partCount; i++) { //if colliding if (isColliding(particles[i].x, sphereRadius)>0) { glm::dvec3 cp; double depth; glm::dvec3 normal; //get collision data collisionData(cp, depth, normal, particles[i].x, sphereRadius); //collision Response double slip = 0.0; particles[i].x = cp; particles[i].v = particles[i].v - (1.0 + slip*depth / (dt* glm::length(particles[i].v)))* glm::dot(particles[i].v, normal)*normal; } } previous_time = current_time; if (running) glutSetWindowTitle("SPH running"); else glutSetWindowTitle("SPH paused"); glutPostRedisplay(); }
bool Collider::isColliding(Collider* _first, Collider* _second){ //Delegate to the proper function call. //Don't touch unless yo know what yo doin' if (_first && _second) { if (_first->type == ColliderType::Sphere){ if (_second->type == Collider::Sphere){ return isColliding(((SphereCollider*)_first), ((SphereCollider*)_second)); } else if (_second->type == ColliderType::BoundedPlane){ return isColliding(((SphereCollider*)_first), ((PlaneCollider*)_second)); } else if (_second->type == ColliderType::Cube){ return isColliding(((SphereCollider*)_first), ((CubeCollider*)_second)); } } else if (_first->type == ColliderType::BoundedPlane){ if (_second->type == Collider::Sphere){ return isColliding(((SphereCollider*)_second), ((PlaneCollider*)_first)); } else if (_second->type == ColliderType::BoundedPlane){ return isColliding(((PlaneCollider*)_first), ((PlaneCollider*)_second)); } else if (_second->type == ColliderType::Cube){ return isColliding(((PlaneCollider*)_first), ((CubeCollider*)_second)); } } else if (_first->type == ColliderType::Cube){ if (_second->type == Collider::Sphere){ return isColliding(((SphereCollider*)_second), ((CubeCollider*)_first)); } else if (_second->type == ColliderType::BoundedPlane){ return isColliding(((PlaneCollider*)_second), ((CubeCollider*)_first)); } else if (_second->type == ColliderType::Cube){ return isColliding(((CubeCollider*)_first), ((CubeCollider*)_second)); } } } else return false; }
//detects collision with AABB method void InGame::detectCollision(SpawnableObject*& object,Snake &snake) { Vector2f position1 = snake.snake.at(HEAD)->snakeSegment.getPosition(); Vector2f position2 = object->shape.getPosition(); bool b = isColliding(object, snake.snake.at(0)); if( b == true) { object->onCollision(); delete object; object = NULL; } }
void Stalfos::movement(std::vector<std::shared_ptr<GameObject>>* worldMap) { Point offsets(getXOffset(), getYOffset()); switch (dir){ case Direction::Down: { Point pt(position.x, position.y + minStep); if (!isColliding(worldMap, fullMask, offsets) && !isOutsideRoomBound(pt)) position.y += minStep; else getNextDirection(Direction::Down); break; } case Direction::Up: { Point pt(position.x, position.y - minStep); if (!isColliding(worldMap, fullMask, offsets) && !isOutsideRoomBound(pt)) position.y -= minStep; else getNextDirection(Direction::Up); break; } case Direction::Left: { Point pt(position.x - minStep, position.y); if (!isColliding(worldMap, fullMask, offsets) && !isOutsideRoomBound(pt)) position.x -= minStep; else getNextDirection(Direction::Left); break; } case Direction::Right: { Point pt(position.x + minStep, position.y); if (!isColliding(worldMap, fullMask, offsets) && !isOutsideRoomBound(pt)) position.x += minStep; else getNextDirection(Direction::Right); break; } } }
void ColliderManager::updateList() { glm::vec3 mtv; if (colliderUpdateList.size() > 1) for (int i = 1; i < colliderUpdateList.size(); i++) { if (isColliding(*(colliderUpdateList[i]), *(colliderUpdateList[i-1]), mtv)) { // MTV contains the mininum translation vector // Use getPointOfCollision to get the point of contact and use it to resolve collision std::cout << "Objects are colliding"; std::cout << "ids: " << colliderUpdateList[i]->id << " " << colliderUpdateList[i - 1]->id; } } }
void Spaceship::move(Ogre::Vector3 playerPos,Ogre::Camera *camera, int *hp) { // Move ship to its next position // Check for collision with player and other ships Ogre::Vector3 pos = camera->getPosition(), forw, right, up; forw = camera->getDerivedOrientation() * Ogre::Vector3(0,0,-1); if (pathCount < PATH_SIZE) { if (isColliding(fPath[PATH_SIZE])) { calcNewPath(); } if (isColliding(fPath[pathCount])) { nextPathPos(); } if(isColliding(camera->getPosition())){ camera->setPosition(pos - forw); *hp-=5; } moveTo(fPath[pathCount]); } else { calcNewPath(); move(playerPos,camera,hp); } }
//Fills the provided array with resultant points (points //contained in the specified range). Returns total results //Pass in the maximum for the array as well as the index //this function should start at (usually 0) unsigned int queryRange(aabb& range, T* results, int& currentIndex, int maxPoints) { //std::cout << bounds.x << " , " << bounds.y << " w " << bounds.w << " h " << bounds.h << " \n"; unsigned int totalResults = 0; //Make sure the array isn't full if (currentIndex >= maxPoints) { std::cout << "WARNING: queryPoints(): Results array full! (Max points = "<< maxPoints<< ")\n"; return totalResults; } //Make sure range is touching this node if (!isColliding(&range, &bounds)) { return 0; } //Add points in this node to results if contained in range for (typename std::list<QuadPoint<T> >::iterator it = data.begin(); it!=data.end(); ++it) { if (isPointInRange((*it).x, (*it).y, range)) { if (currentIndex < maxPoints) { results[currentIndex] = (*it).data; totalResults++; currentIndex++; } else { std::cout << "WARNING: queryPoints(): Results array full! (Max points = "<< maxPoints<< ")\n"; return totalResults; } } } //Let all child nodes (if any) add points if (!tL) { return totalResults; } totalResults += tL->queryRange(range, results, currentIndex, maxPoints); totalResults += tR->queryRange(range, results, currentIndex, maxPoints); totalResults += bL->queryRange(range, results, currentIndex, maxPoints); totalResults += bR->queryRange(range, results, currentIndex, maxPoints); return totalResults; }
bool FootstepGraph::isSuccessable(StatePtr current_state, StatePtr previous_state) { if (global_transition_limit_) { if (!global_transition_limit_->check(zero_state_, current_state)) { return false; } } if (transition_limit_) { if (!transition_limit_->check(previous_state, current_state)) { return false; } } if (use_obstacle_model_) { return !isColliding(current_state, previous_state); } return true; }
void Mine::update() { if (exists) { for (auto o : allUpdateObjects) { if (o != (GameObject*)this && isColliding(*(GameObject*)this, *o)) { explode(); if( std::find(allPlayers.begin(), allPlayers.end(), (Player*)o) != allPlayers.end() ) { ((Player*) o)->hit(); } } } sight->position = this->mModel.position; sight->position.y += 1.5f; } else { if (glfwGetTime() > respawntime) { mModel.position = spawn(); exists = true; } } }
void wp_gren_proj::updateSprite() { if (isOnGround()) { setBounds(2, 8, 5, -4); //bigger collision to take out neighbouring platforms for (vector<spriteObject*>::iterator it = sm->gameSprites.begin(); it != sm->gameSprites.end(); ++it) { if (dynamic_cast<floorTile*>(*it) != NULL && isColliding(*it)) { //check if the destroyed floor was under a player gameManager *gm = dynamic_cast<gameManager *>(sm); if (gm->player1->isStandingOn(*it)) gm->player1->groundDeleted(Player::CS_GRENFALL); if (gm->player2->isStandingOn(*it)) gm->player2->groundDeleted(Player::CS_GRENFALL); (*it)->destroy(); } } destroy(); return; } if (getx() < -16 || getx() > 271) //out of the screen now, dont wanna see the death FX either { destroy(); return; } else if (y >= (s32)SCREENH+4096) //fell out of bottom so make a splash, go low enough to hide death FX { #ifdef __WITHSOUND playSound(&owner->gm->smallSplash); #endif //GFX warning! u8 f[3] = {13, 14, 15}; vector<u8> temp(f, f+3); sm->createSingleFireSprite(owner->gm->FXSprite.palleteID, owner->gm->FXSprite.spriteData, temp, TICKSPERFRAME*2, getx(), gameManager::MALLOWYPOS, OBJ_SIZE_32X32, 16, 16); destroy(); return; } massObject::updateSprite(); }
void EntityManager::interact() { //kör interact mot alla som krockar for(EntityVector::size_type i = 0; i < mDynamicEntities.size(); ++i) { for(EntityVector::size_type j = 0; j < mEntities.size(); ++j) { if(mDynamicEntities[i] != mEntities[j]) { if(mDynamicEntities[i]->getAliveStatus() && mEntities[j]->getAliveStatus()) { if(isColliding(mDynamicEntities[i], mEntities[j])) { mDynamicEntities[i]->interact(mEntities[j]); mEntities[j]->interact(mDynamicEntities[i]); } } } } } }
int GameObject::getMinimumLineCollisionDistance(Direction pushbackDir, std::vector<std::shared_ptr<GameObject>>* worldMap) { float pushBackMinDistance = 0; sf::Vector2f size(width, height); std::unique_ptr<sf::RectangleShape> pushbackLineCheck = std::make_unique<sf::RectangleShape>(); pushbackLineCheck->setPosition(position.x, position.y); pushbackLineCheck->setSize(size); Point pt; for(pushBackMinDistance = 0; pushBackMinDistance < pushBackMaxDistance; pushBackMinDistance++){ if(pushbackDir == Direction::Up) pt.setPoint(0, -pushBackMinDistance); else if(pushbackDir == Direction::Down) pt.setPoint(0, pushBackMinDistance); else if(pushbackDir == Direction::Right) pt.setPoint(pushBackMinDistance, 0); else if(pushbackDir == Direction::Left) pt.setPoint(-pushBackMinDistance, 0); if(isColliding(worldMap, pushbackLineCheck, pt)) break; } return pushBackMinDistance; }
void PointLight::draw() { // 1. OcclusionMap m_occlusionMap->begin(); glDisable(GL_BLEND); const auto& objects = SimpleEngine::get()->getActiveScene()->getObjects(); for (const auto& object : objects) { if (object->isLightOccluder() and isColliding(object.get())) { object->draw(); } } m_occlusionMap->end(); // 2. ShadowMap m_shadowMap->begin(); m_shadowMapRenderer->draw(); m_shadowMap->end(); glEnable(GL_BLEND); // 3. Render shadows m_lightMap->begin(); m_shadowRenderer->draw(); m_lightMap->end(); // 4. Out m_finalSprite->draw(); }
bool Tetramino::tryTurn(Direction dir) { if (dir == TETRIS_DIR_UP || dir == TETRIS_DIR_DOWN) return false; int oldreal = _realrot; int oldrot = _rotation; if (dir == TETRIS_DIR_LEFT) _realrot = --_realrot; else _realrot = ++_realrot; _rotation = abs(_realrot) % 4; updateCellRotation(); if(isColliding()) { _rotation = oldrot; _realrot = oldreal; updateCellRotation(); return false; } _game->updateGrid(); return true; }
void Vehicle::processCollisions(void) { if(isColliding()) { for(int x = 0; x < (int)currentCollisions.size(); x++) { CollidableType c = currentCollisions[x]; if(c == ITEM_MINIGUN || c == ITEM_MINE || c == ITEM_MISSILE || c == ITEM_BOMB || c == ITEM_HEALTH || c == ITEM_SPEED_MISSILE || c == ITEM_POWER_MISSILE) { cT = c; //Copy the item type to vehicle timer.startTimer(); //Start timer (for weapon deployment like mines) if(c == ITEM_MINIGUN) { ammoRemaining = MINIGUN_MAX_ROUNDS; totalAmmo = MINIGUN_MAX_ROUNDS; } else if(c == ITEM_MINE) { ammoRemaining = MINE_MAX_ROUNDS; totalAmmo = MINE_MAX_ROUNDS; } else if(c == ITEM_MISSILE) { ammoRemaining = MISSILE_MAX_ROUNDS; totalAmmo = MISSILE_MAX_ROUNDS; } else if(c == ITEM_BOMB) { ammoRemaining = BOMB_MAX_ROUNDS; totalAmmo = BOMB_MAX_ROUNDS; } else if(c == ITEM_SPEED_MISSILE) { ammoRemaining = SMISSILE_MAX_ROUNDS; totalAmmo = SMISSILE_MAX_ROUNDS; } else if(c == ITEM_POWER_MISSILE) { ammoRemaining = PMISSILE_MAX_ROUNDS; totalAmmo = PMISSILE_MAX_ROUNDS; } else if(c == ITEM_HEALTH) { float health = getHP(); health = health + ((100.0f - health)*0.5f); setHP(health); ammoRemaining = 0.0f; cT = NONE; } } if(currentCollisions.at(x) == OBSTACLE) { if(myVehicleNum == 0) { position[0] = position[0] - velocity[0]; position[2] = position[2] - velocity[2]; speed = 0.0f; } } if(currentCollisions[x] == VEHICLE) { color[3] = 0.1f; } #ifndef GOD_MODE if(currentCollisions[x] == PROJECTILE_MINIGUN) { hitPoints -= MINIGUN_DAMAGE; } else if(currentCollisions[x] == PROJECTILE_MINE) { hitPoints -= MINE_DAMAGE; } else if(currentCollisions[x] == PROJECTILE_MISSILE) { hitPoints -= MISSILE_DAMAGE; } else if(currentCollisions[x] == PROJECTILE_BOMB) { hitPoints -= BOMB_DAMAGE; } else if(currentCollisions[x] == PROJECTILE_SPEED_MISSILE) { hitPoints -= SMISSILE_DAMAGE; } else if(currentCollisions[x] == PROJECTILE_POWER_MISSILE) { hitPoints -= PMISSILE_DAMAGE; } #endif if(hitPoints<=0.0f) //We're dead. { clearCurrentCollisions(); //to allow vehicles to respawn comment shouldBeDeleted //and uncomment the reset player call physicsEnabled = false; shouldBeDeleted = true; hitPoints = 0.0f; //so we can't go below zero health! } } } else { color[3] = 1.0f; } clearCurrentCollisions(); }
bool Collider::operator|(const Collider& other) const { return isColliding(other); }
void EntityManager::handleCollisions() { // Evade from other enemies. for(std::list<Enemy*>::iterator i = m_enemies.begin(); i != m_enemies.end(); i++) { for(std::list<Enemy*>::iterator j = m_enemies.begin(); j != m_enemies.end(); j++) { if(isColliding(*i, *j)) { (*i)->handleCollision(*j); (*j)->handleCollision(*i); } } } // Determine shot enemies. for(std::list<Enemy*>::iterator i = m_enemies.begin(); i != m_enemies.end(); i++) { for(std::list<Bullet*>::iterator j = m_bullets.begin(); j != m_bullets.end(); j++) { if(isColliding(*i, *j)) { (*i)->wasShot(); (*i)->setExpired(); } } } // Determine enemy crashing into player. for(std::list<Enemy*>::iterator i = m_enemies.begin(); i != m_enemies.end(); i++) { if(isColliding(*i, PlayerShip::getInstance()) && (*i)->getIsActive()) { PlayerShip::getInstance()->kill(); for(std::list<Enemy*>::iterator j = m_enemies.begin(); j != m_enemies.end(); j++) { (*j)->wasShot(); } EnemySpawner::getInstance()->reset(); break; } } // Determine enemy crashing into player. for(std::list<BlackHole *>::iterator i = m_blackHoles.begin(); i != m_blackHoles.end(); i++) { // Kill enemies in the way. for(std::list<Enemy*>::iterator j = m_enemies.begin(); j != m_enemies.end(); j++) { if((*j)->getIsActive() && isColliding(*i, *j)) { (*j)->wasShot(); } } // Kill bullets in the way. for(std::list<Bullet*>::iterator j = m_bullets.begin(); j != m_bullets.end(); j++) { if(isColliding(*i, *j)) { (*j)->setExpired(); (*i)->wasShot(); } } // Kill player if collide. if(isColliding(PlayerShip::getInstance(), *i)) { KillPlayer(); } } }
bool CCollidable::isColliding(CCollidable *c) { return isColliding(c->getContainer()); }
int main() { sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Pickin' Gems"); window.SetFramerateLimit(30); window.SetIcon(gem_icon.width, gem_icon.height, gem_icon.pixel_data); sf::Image grassImage; grassImage.LoadFromFile("grass.png"); grassImage.SetSmooth(false); sf::Sprite grass; grass.SetImage(grassImage); sf::Image gemImage; gemImage.LoadFromFile("gem.png"); gemImage.CreateMaskFromColor(sf::Color(255, 0, 255)); gemImage.SetSmooth(false); sf::Sprite gem; gem.SetImage(gemImage); sf::Image player1Image; player1Image.LoadFromFile("ayne.png"); player1Image.CreateMaskFromColor(sf::Color(255, 0, 255)); player1Image.SetSmooth(false); sf::Sprite player1(player1Image); sf::Image player2Image; player2Image.LoadFromFile("elliot.png"); player2Image.CreateMaskFromColor(sf::Color(255, 0, 255)); player2Image.SetSmooth(false); sf::Sprite player2(player2Image); sf::Image pressEnterToStartImage; pressEnterToStartImage.LoadFromFile("pressEnterToStart.png"); pressEnterToStartImage.SetSmooth(false); sf::Sprite pressEnterToStart(pressEnterToStartImage); sf::Image humanSelectedImage; humanSelectedImage.LoadFromFile("humanSelected.png"); humanSelectedImage.SetSmooth(false); sf::Sprite humanSelectedSprite(humanSelectedImage); sf::Image computerSelectedImage; computerSelectedImage.LoadFromFile("computerSelected.png"); computerSelectedImage.SetSmooth(false); sf::Sprite computerSelectedSprite(computerSelectedImage); sf::Image gameOverScreenImage; gameOverScreenImage.LoadFromFile("gameOverScreen.png"); gameOverScreenImage.SetSmooth(false); sf::Sprite gameOverScreen(gameOverScreenImage); sf::Music backgroundMusic; backgroundMusic.OpenFromFile("background.ogg"); backgroundMusic.SetLoop(true); sf::SoundBuffer gemPickupBuffer; gemPickupBuffer.LoadFromFile("gemCollect.wav"); sf::Sound gemPickup; gemPickup.SetBuffer(gemPickupBuffer); sf::Font font; font.LoadFromFile("Halo11.ttf"); sf::String player1ScoreToPrint; sf::String player2ScoreToPrint; sf::String timerPrint; sf::String gameOverPrint; player1ScoreToPrint.SetFont(font); player1ScoreToPrint.SetSize(24); player2ScoreToPrint.SetFont(font); player2ScoreToPrint.SetSize(24); timerPrint.SetFont(font); timerPrint.SetSize(24); gameOverPrint.SetFont(font); gameOverPrint.SetSize(24); float player1Frame = 1; float player2Frame = 1; int player1Score = 0; int player2Score = 0; char buffer1[256]; char buffer2[256]; char buffer3[256]; char buffer4[256]; sf::Vector2f player1Pos; sf::Vector2f player2Pos; enum Direction {DOWN = 0, UP = 1, LEFT = 2, RIGHT = 3}; enum State {MAIN_MENU = 0, PLAYER_SELECT = 1, GAME = 2, GAME_OVER = 3}; State gameState = MAIN_MENU; bool humanSelected = true; bool computerSelected = false; bool enterPressed = false; bool downPressed = false; bool upPressed = false; bool backgroundMusicPlaying = true; Direction player1Direction = DOWN; Direction player2Direction = DOWN; bool player1Moving = false; bool player2Moving = false; bool player1Animating = false; bool player2Animating = false; sf::Vector2f gemPos; srand(time(NULL)); gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); int time = 1800; bool gameOver = false; bool fullscreen = false; while (window.IsOpened()) { sf::Event event; while (window.GetEvent(event)) { if (event.Type == sf::Event::Closed) { window.Close(); } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape)) { window.Close(); } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Return)) { enterPressed = true; } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Up)) { upPressed = true; } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Down)) { downPressed = true; } } switch (gameState) { case MAIN_MENU: window.Draw(pressEnterToStart); if (enterPressed) { enterPressed = false; gameState = PLAYER_SELECT; } break; case PLAYER_SELECT: if (humanSelected) { window.Draw(humanSelectedSprite); } else if (computerSelected) { window.Draw(computerSelectedSprite); } if (upPressed) { if (computerSelected) { computerSelected = false; humanSelected = true; } else if (humanSelected) { humanSelected = false; computerSelected = true; } upPressed = false; } else if (downPressed) { if (humanSelected) { humanSelected = false; computerSelected = true; } else if (computerSelected) { computerSelected = false; humanSelected = true; } downPressed = false; } if (enterPressed) { enterPressed = false; gameState = GAME; } break; case GAME: { --time; if (backgroundMusicPlaying) { backgroundMusicPlaying = false; backgroundMusic.Play(); } for (int i = 0; i < 640 / 32; i++) { for (int j = 0; j < 480 / 32; j++) { grass.SetPosition(i * 32, j * 32); window.Draw(grass); } } gem.SetPosition(gemPos); if (window.GetInput().IsKeyDown(sf::Key::Left)) { player1Direction = LEFT; player1Animating = true; player1.Move(-3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::Right)) { player1Direction = RIGHT; player1Animating = true; player1.Move(3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::Up)) { player1Direction = UP; player1Animating = true; player1.Move(0, -3); } else if (window.GetInput().IsKeyDown(sf::Key::Down)) { player1Direction = DOWN; player1Animating = true; player1.Move(0, 3); } if (humanSelected) { if (window.GetInput().IsKeyDown(sf::Key::A)) { player2Direction = LEFT; player2Animating = true; player2.Move(-3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::D)) { player2Direction = RIGHT; player2Animating = true; player2.Move(3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::W)) { player2Direction = UP; player2Animating = true; player2.Move(0, -3); } else if (window.GetInput().IsKeyDown(sf::Key::S)) { player2Direction = DOWN; player2Animating = true; player2.Move(0, 3); } } else if (computerSelected) { if ((int)player2Pos.x < (int)gemPos.x) { if (gemPos.x - player2Pos.x < 2) { player2.Move(1, 0); } else { player2.Move(2, 0); } player2Direction = RIGHT; player2Animating = true; } else if ((int)player2Pos.y > (int)gemPos.y) { if (player2Pos.y - gemPos.y < 2) { player2.Move(0, -1); } else { player2.Move(0, -2); } player2Direction = UP; player2Animating = true; } else if ((int)player2Pos.x > (int)gemPos.x) { if (player2Pos.x - gemPos.x < 2) { player2.Move(-1, 0); } else { player2.Move(-2, 0); } player2Direction = LEFT; player2Animating = true; } else if ((int)player2Pos.y < (int)gemPos.y) { if (gemPos.y - player2Pos.y < 2) { player2.Move(0, 1); } else { player2.Move(0, 2); } player2Direction = DOWN; player2Animating = true; } else if ((int)player2Pos.x > (int)gemPos.x) { if (player2Pos.x - gemPos.x < 2) { player2.Move(-1, 0); } else { player2.Move(-2, 0); } player2Direction = LEFT; player2Animating = true; } } if (player1Animating) { player1Frame += 0.25; if (player1Frame > 3) { player1Frame = 0; } player1Animating = false; } if (player2Animating) { player2Frame += 0.25; if (player2Frame > 3) { player2Frame = 0; } player2Animating = false; } player1Pos = player1.GetPosition(); player2Pos = player2.GetPosition(); if (player1Pos.x < 0) { player1.SetX(0); } else if (player1Pos.x + 32 > 640) { player1.SetX(640 - 32); } if (player1Pos.y < 0) { player1.SetY(0); } else if (player1Pos.y + 48 > 480) { player1.SetY(480 - 48); } if (player2Pos.x < 0) { player2.SetX(0); } else if (player2Pos.x + 32 > 640) { player2.SetX(640 - 32); } if (player2Pos.y < 0) { player2.SetY(0); } else if (player2Pos.y + 48 > 480) { player2.SetY(480 - 48); } if (isColliding(getRegionCoordinates(gemPos, 32, 32), getRegionCoordinates(player1Pos, 32, 48))) { gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); gemPickup.Play(); player1Score += 10; } if (isColliding(getRegionCoordinates(gemPos, 32 + 3, 32 + 3), getRegionCoordinates(player2Pos, 32, 48))) { gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); gemPickup.Play(); player2Score += 10; } sprintf(buffer1, "Player 1's Score: %d", player1Score); sprintf(buffer2, "Player 2's Score: %d", player2Score); sprintf(buffer3, "Time left: %d", time / 30); player1ScoreToPrint.SetText(buffer1); player2ScoreToPrint.SetText(buffer2); timerPrint.SetText(buffer3); player1ScoreToPrint.SetColor(sf::Color(0, 0, 0)); player2ScoreToPrint.SetColor(sf::Color(0, 0, 0)); timerPrint.SetColor(sf::Color(0, 0, 0)); player1ScoreToPrint.SetX(0); player1ScoreToPrint.SetY(0); player2ScoreToPrint.SetX(0); player2ScoreToPrint.SetY(24); timerPrint.SetX(0); timerPrint.SetY(48); int player1SpritesheetX = (int)player1Frame * 32; int player1SpritesheetY = player1Direction * 48; int player2SpritesheetX = (int)player2Frame * 32; int player2SpritesheetY = player2Direction * 48; player1.SetSubRect(sf::IntRect(player1SpritesheetX, player1SpritesheetY, player1SpritesheetX + 32, player1SpritesheetY + 48)); player2.SetSubRect(sf::IntRect(player2SpritesheetX, player2SpritesheetY, player2SpritesheetX + 32, player2SpritesheetY + 48)); window.Draw(gem); window.Draw(player2); window.Draw(player1); window.Draw(player1ScoreToPrint); window.Draw(player2ScoreToPrint); window.Draw(timerPrint); if (time / 30 == 0) { gameState = GAME_OVER; } break; } case GAME_OVER: { if (player1Score < player2Score) { sprintf(buffer4, "Congratulations, Player 2! You win!"); } else if (player1Score > player2Score) { sprintf(buffer4, "Congratulations, Player 1! You win!"); } else { sprintf(buffer4, "It's a tie!"); } gameOverPrint.SetText(buffer4); gameOverPrint.SetColor(sf::Color(0, 0, 0)); sf::FloatRect rect(gameOverPrint.GetRect()); sf::Vector2f pos(window.GetWidth() / 2 - rect.GetWidth() / 2, window.GetHeight() / 2 - rect.GetHeight() / 2); gameOverPrint.SetPosition(pos); window.Draw(gameOverScreen); window.Draw(gameOverPrint); if (enterPressed) { enterPressed = false; gameState = MAIN_MENU; time = 1800; player1Score = 0; player2Score = 0; player1Frame = 1; player2Frame = 1; player1.SetPosition(0, 0); player2.SetPosition(0, 0); player1Direction = DOWN; player2Direction = DOWN; upPressed = false; downPressed = false; humanSelected = true; } break; } } window.Display(); window.Clear(); } return 0; }