Point Point::operator-(const Point &p) { Point result(getX() - p.getX(), getY() - p.getY(), getZ() - p.getZ()); return result; }
void Exp_8_Homework_A(void) { vTaskResume(TimerTask); int i, j; int col, row; int tmp; int keyPressed = FALSE; srand(time(NULL)); for (i = 0; i < BALL_NUM; i++) { for (j = 0; j < BALL_NUM; j++) { tmp = rand() % COIN_NUM + 1; switch (tmp) { case 1: cell[i][j] = COLOR_RED; break; case 2: cell[i][j] = COLOR_YELLOW; break; case 3: cell[i][j] = COLOR_GREEN; break; case 4: cell[i][j] = COLOR_BLUE; break; case 5: cell[i][j] = COLOR_PURPLE; break; case 0: cell[i][j] = COLOR_BLACK; break; } draw_my_box(j, i, cell[i][j]); } } combo = score = 0; while (sec > 0) { scanKeys(); touchRead(&touch); if ((keysHeld() & KEY_TOUCH)&& !keyPressed){ col = getX(touch.px); row = getY(touch.py); if (!checkPang(row, col)) { combo = 0; continue; } combo++; score += (10 + 5 * (combo + 1)); pang(); fallCoin(); for (i = 0; i < BALL_NUM; i++) { for (j = 0; j < BALL_NUM; j++) { draw_my_box(j, i, cell[i][j]); } } keyPressed = TRUE; } if (keyPressed && !(keysHeld() & KEY_TOUCH)) { keyPressed = FALSE; } } if (sec <= 0) decompress(downmainBitmap, BG_GFX_SUB, LZ77Vram); }
void Player::update(float frameTime, LevelController* lc) { // 1-Press NoClip if (noClipButtonReleased && input->isKeyDown(VK_F2)) { noClip = !noClip; noClipButtonReleased = false; } else { noClipButtonReleased = true; } velocityX = getVelocity().x; velocityY = getVelocity().y; // Handle NoClip if (noClip) { if (input->isKeyDown(PLAYER_RIGHT)) { velocityX = playerNS::NOCLIP_SPEED * frameTime; orientation = Right; } else if (input->isKeyDown(PLAYER_LEFT)) { velocityX = -playerNS::NOCLIP_SPEED * frameTime; orientation = Left; } else { velocityX = 0; } if (input->isKeyDown(PLAYER_UP)) { velocityY = -playerNS::NOCLIP_SPEED * frameTime; orientation = Up; } else if (input->isKeyDown(PLAYER_DOWN)) { velocityY = playerNS::NOCLIP_SPEED * frameTime; orientation = Down; } else { velocityY = 0; } velocity = VECTOR2(velocityX, velocityY); frameDelay = 1000000; Item* activeItem = inventory->getActiveItem()->getItem(); if (inventory->getActiveItem()->getItem()->getItemType() == Item::Equipable) { Gun* gun = dynamic_cast<Gun*>(activeItem); if (gun != 0) { gun->update(frameTime, orientation, getX(), getY(), input, lc); } } Entity::update(frameTime); return; } // Set Obj Vars levelController = lc; // Debug Messages OSD::instance()->addLine("Jump Distance: " + std::to_string(jumpdistance) + " / " + std::to_string(playerNS::JUMP_HEIGHT)); OSD::instance()->addLine("Can | Left: " + std::to_string(canMoveLeft(true)) + " | Right: " + std::to_string(canMoveRight(true)) + " | Up: " + std::to_string(canMoveUp(true)) + " | Down: " + std::to_string(canMoveDown(true))); // Stuck Hotfix if (!canMoveLeft() && !canMoveRight() && !canMoveUp() && !canMoveDown()) { setX(spawnPos.x); setY(spawnPos.y); } // Update Guns inventory->update(frameTime, input); // Boss Audio if (lc->getMapX() * -1.0 > 1900) { audio->stopCue(BK_MUSIC); audio->playCue(BOSS_MUSIC); } // Start of Player Movement if (healthStatus != Dead) { if (!canMoveDown()) { if (!input->isKeyDown(PLAYER_UP) && !input->isKeyDown(PLAYER_JUMP)) canJump = true; canFall = false; falling = false; } else { canFall = true; falling = true; } // Move Left and Right if (input->isKeyDown(PLAYER_RIGHT) && canMoveRight()) { velocityX = playerNS::SPEED * frameTime; while (!canMoveRight()) { spriteData.x -= 0.1; velocityX = 0; } orientation = Right; } else if (input->isKeyDown(PLAYER_LEFT) && canMoveLeft()) { velocityX = -playerNS::SPEED * frameTime; while (!canMoveLeft()) { spriteData.x += 0.1; velocityX = 0; } orientation = Left; } else { velocityX = 0; if (input->isKeyDown(PLAYER_UP)) { orientation = Up; } if (input->isKeyDown(PLAYER_DOWN)) { orientation = Down; } } // Handle Jumping if (jumping || (((input->isKeyDown(PLAYER_JUMP) || input->isKeyDown(PLAYER_UP)) && canMoveUp() && canJump))) { jumpdistance = jumpOriginY - getY(); if (canJump && !jumping) jumpOriginY = getY(); if (jumpdistance > playerNS::JUMP_HEIGHT || !canMoveUp()) { jumping = false; canJump = false; falling = true; } else { if (!jumping) velocityY = -playerNS::JUMP_SPEED * frameTime; else velocityY += 0.5 * frameTime; jumping = true; canJump = false; } } if (!jumping) jumpOriginY = getY(); if (falling && !jumping) { if (canMoveDown()) { velocityY = playerNS::FALLING_SPEED * frameTime; } else { velocityY = 0; } } // Handle Stuck while (canMoveUp() && !canMoveDown() && !canMoveLeft() && !canMoveRight()) { spriteData.y -= 0.1; } while (!canMoveUp() && !canMoveDown() && !canMoveLeft() && canMoveRight()) { spriteData.x += 0.1; } while (!canMoveUp() && !canMoveDown() && canMoveLeft() && !canMoveRight()) { spriteData.x -= 0.1; } // Final Sanity Check if (!canMoveLeft() && velocityX < 0 || !canMoveRight() && velocityX > 0) velocityX = 0; if (!canMoveUp() && velocityY < 0 || !canMoveDown() && velocityY > 0) velocityY = 0; setVelocity(VECTOR2(velocityX, velocityY)); // Handle Orientations if (input->isKeyDown(PLAYER_UP)) orientation = Up; else if (input->isKeyDown(PLAYER_DOWN)) orientation = Down; switch (orientation) { case Right: currentFrame = 953; spriteData.flipHorizontal = true; break; case Down: currentFrame = 954; break; case Left: currentFrame = 953; spriteData.flipHorizontal = false; break; case Up: currentFrame = 952; break; } // Draw Items Item* activeItem = inventory->getActiveItem()->getItem(); if (inventory->getActiveItem()->getItem()->getItemType() == Item::Equipable) { Gun* gun = dynamic_cast<Gun*>(activeItem); if (gun != 0) { gun->update(frameTime, orientation, getX(), getY(), input, lc); } } // Crate Collision if (lc->collidedWithCrate() == 1 && lc->getCrateItem() != -1) { audio->playCue(RELOAD); if (lc->collidedWithCrate() == 1 && lc->getCrateItem() != -1) { int itemid = lc->getCrateItem(); InventoryItem *invItem; std::vector<InventoryItem*>* itemList = inventory->getItems(); switch (itemid) { case playerNS::ItemType::shotGun: shotgun = new Shotgun(); shotgun->initialize(gameptr, 136, 41, 2, gunTexture); shotgun->setCurrentFrame(6); invItem = new InventoryItem(shotgun); break; case playerNS::ItemType::machineGun: machineGun = new MachineGun(); machineGun->initialize(gameptr, 136, 41, 2, gunTexture); machineGun->setCurrentFrame(0); invItem = new InventoryItem(machineGun); break; case 3: break; } for (int i = 0; i < itemList->size(); i++) { InventoryItem *iItem = itemList->at(i); Item* item = iItem->getItem(); Item* newItem = invItem->getItem(); if (item->getItemType() == Item::Equipable && newItem->getItemType() == Item::Equipable) { Gun* gunInvItem = dynamic_cast<Gun*>(item); Gun* gunNewItem = dynamic_cast<Gun*>(newItem); if (gunInvItem->getGunId() == gunNewItem->getGunId()) { gunInvItem->addAmmo(); lc->setCrateCollided(0); return; // Should this be return or break? } } else if (item->getItemType() == Item::Usable && newItem->getItemType() == Item::Usable) { lc->setCrateCollided(0); return; } // Should this be return or break? } inventory->addItem(invItem); lc->setCrateCollided(0); lc->setCrateItem(-1); } } Entity::update(frameTime); } }
Vector2 normalized() const { float m = this->magnitude(); return Vector2(getX() / m, getY() / m); }
/** * Handles moving over the minimap. * Will change the camera center when the mouse is moved in mouse-moving mode. * @param action Pointer to an action. * @param state State that the action handlers belong to. */ void MiniMapView::mouseOver(Action *action, State *state) { InteractiveSurface::mouseOver(action, state); if (_isMouseScrolling && action->getDetails()->type == SDL_MOUSEMOTION) { // The following is the workaround for a rare problem where sometimes // the mouse-release event is missed for any reason. // However if the SDL is also missed the release event, then it is to no avail :( // (checking: is the dragScroll-mouse-button still pressed?) if (0==(SDL_GetMouseState(0,0)&SDL_BUTTON(Options::battleDragScrollButton))) { // so we missed again the mouse-release :( // Check if we have to revoke the scrolling, because it was too short in time, so it was a click if ((!_mouseMovedOverThreshold) && ((int)(SDL_GetTicks() - _mouseScrollingStartTime) <= (Options::dragScrollTimeTolerance))) { _camera->centerOnPosition(_posBeforeMouseScrolling); _redraw = true; } _isMouseScrolled = _isMouseScrolling = false; stopScrolling(action); return; } _isMouseScrolled = true; // Set the mouse cursor back SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); SDL_WarpMouse(_xBeforeMouseScrolling, _yBeforeMouseScrolling); SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE); // Check the threshold _totalMouseMoveX += action->getDetails()->motion.xrel; _totalMouseMoveY += action->getDetails()->motion.yrel; if (!_mouseMovedOverThreshold) _mouseMovedOverThreshold = ((std::abs(_totalMouseMoveX) > Options::dragScrollPixelTolerance) || (std::abs(_totalMouseMoveY) > Options::dragScrollPixelTolerance)); // Calculate the move int newX, newY; int scrollX, scrollY; if (Options::battleDragScrollInvert) { scrollX = action->getDetails()->motion.xrel; scrollY = action->getDetails()->motion.yrel; } else { scrollX = -action->getDetails()->motion.xrel; scrollY = -action->getDetails()->motion.yrel; } _mouseScrollX += scrollX; _mouseScrollY += scrollY; newX = _posBeforeMouseScrolling.x + _mouseScrollX / action->getXScale() / 4; newY = _posBeforeMouseScrolling.y + _mouseScrollY / action->getYScale() / 4; // Keep the limits... if (newX < -1 || _camera->getMapSizeX() < newX) { _mouseScrollX -= scrollX; newX = _posBeforeMouseScrolling.x + _mouseScrollX / 4; } if (newY < -1 || _camera->getMapSizeY() < newY) { _mouseScrollY -= scrollY; newY = _posBeforeMouseScrolling.y + _mouseScrollY / 4; } // Scrolling _camera->centerOnPosition(Position(newX,newY,_camera->getViewLevel())); _redraw = true; // We don't want to look the mouse-cursor jumping :) if (Options::battleDragScrollInvert) { action->getDetails()->motion.x = _xBeforeMouseScrolling; action->getDetails()->motion.y = _yBeforeMouseScrolling; } else { Position delta(-scrollX, -scrollY, 0); int barWidth = _game->getScreen()->getCursorLeftBlackBand(); int barHeight = _game->getScreen()->getCursorTopBlackBand(); int cursorX = _cursorPosition.x + delta.x; int cursorY =_cursorPosition.y + delta.y; _cursorPosition.x = std::min((int)Round((getX() + getWidth()) * action->getXScale()) + barWidth, std::max((int)Round(getX() * action->getXScale()) + barWidth, cursorX)); _cursorPosition.y = std::min((int)Round((getY() + getHeight()) * action->getYScale()) + barHeight, std::max((int)Round(getY() * action->getYScale()) + barHeight, cursorY)); action->getDetails()->motion.x = _cursorPosition.x; action->getDetails()->motion.y = _cursorPosition.y; } _game->getCursor()->handle(action); } }
Vector2 cross() const { return Vector2(-getY(), getX()); }
float magnitude() const { return ::sqrt((getX() * getX()) + (getY() * getY())); }
char needsUpdate(Ball theBall) { return (getX(theBall) != getPrevX(theBall) || getY(theBall) != getPrevY(theBall)); //returns 1 if the position on the screen needs to change }
// If the player doesn't move the character it will start to move around the room in randomly selected directions void Character::moveCharacter(const Uint8* keyboardState) { // checks for keyboard input if there is none it assigns a random directions chooseDirection(keyboardState); // if the direction will keep the charcter on screen and is part of a room move Character down if (direction == 0 && getY() + getSpeed() < windowHeight && isCellARoom(getX(), getY() + getSpeed())) { // If the Characer is wandering also check is the cell is a door if (isWandering == true && isCellADoor(getX(), getY() + getSpeed())) direction = rand() % 4; else setY(getY() + getSpeed()); } // if the direction will keep the charcter on screen and is part of a room move Character up else if (direction == 1 && (getY() + getSpeed()) > 0 && isCellARoom(getX(), getY() - getSpeed())) { // If the Characer is wandering also check is the cell is a door if (isWandering == true && isCellADoor(getX(), getY() - getSpeed())) direction = rand() % 4; else setY(getY() - getSpeed()); } // if the direction will keep the charcter on screen and is part of a room move Character right else if (direction == 2 && (getX() + getSpeed()) < windowWidth && isCellARoom(getX() + getSpeed(), getY())) { // If the Characer is wandering also check is the cell is a door if (isWandering == true && isCellADoor(getX() + getSpeed(), getY())) direction = rand() % 4; else setX(getX() + getSpeed()); } // if the direction will keep the charcter on screen and is part of a room move Character left else if (direction == 3 && (getX() - getSpeed()) > 0 && isCellARoom(getX() - getSpeed(), getY())) { // If the Characer is wandering also check is the cell is a door if (isWandering == true && isCellADoor(getX() - getSpeed(), getY())) direction = rand() % 4; else setX(getX() - getSpeed()); } // If Character cannot move in current direction randomly choose a new one else { direction = rand() % 4; } }
int main(int argc, char* argv[]) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // horizontal & vertical velocity double xVelocity = (drand48() - .5) * 4; double yVelocity = 2; // check for GODMODE bool godMode = false; if (argc == 2) { if (strcmp(argv[1], "GOD") == 0) { godMode = true; } } // keep playing until game over while (lives > 0 && bricks > 0) { GObject object = detectCollision(window, ball); if (object != NULL) { // determine behavior based on collided object if (object == paddle) { // bounce ball back up and change bounce angle based on collision location with paddle yVelocity = -yVelocity; xVelocity = ((getX(ball) + RADIUS) - (getX(paddle) + getWidth(paddle) / 2)) / 10; } else if (object != label) { // adds points based on which row brick is from points += ROWS - (getY(object) - 30) / (BRICK_HEIGHT + BRICK_SEP); removeGWindow(window, detectCollision(window, ball)); yVelocity = -yVelocity; // decreases paddle size slowly based on remaining bricks, minimum of half original size if (getWidth(paddle) > PADDLE_WIDTH / 2) { setSize(paddle, PADDLE_WIDTH * (( 2.0 * (ROWS * COLS) - points) / (2.0 * (ROWS * COLS))), PADDLE_HEIGHT); } updateScoreboard(window, label, points); bricks--; } } move(ball, xVelocity, yVelocity); pause(10); // check for collision with edges if (getX(ball) + getWidth(ball) >= WIDTH || getX(ball) <= 0) { xVelocity = -xVelocity; } if (getY(ball) <= 0) { yVelocity = -yVelocity; } // reset ball and reduce lives if ball touches bottom if (getY(ball) + getHeight(ball) >= HEIGHT) { lives--; waitForClick(); setLocation(ball, WIDTH / 2, HEIGHT / 2); } // if god mode is not active, move paddle with mouse, else paddle moves automagically if (godMode == false) { // move paddle with mouse GEvent event = getNextEvent(MOUSE_EVENT); if (event != NULL) { if (getEventType(event) == MOUSE_MOVED) { setLocation(paddle, getX(event) - (PADDLE_WIDTH / 2), PADDLE_OFFSET); } } } else { // drand used to encourage variety in ball angle to finish game faster setLocation(paddle, (getX(ball) + RADIUS) - (getWidth(paddle) / 2) - (drand48() - .5) * 9, PADDLE_OFFSET); } } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
void PersonalizePageComponent::paint(Graphics &g){ auto bounds = getLocalBounds(); g.fillAll(bgColor); g.drawImage(bgImage,bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0, 0, bgImage.getWidth(), bgImage.getHeight(), false); }
/* * Validate if the move is possible */ bool LevelManager::onPreMove(Moveable& obj, Position next) { auto current = obj.getPosition(); if (m_actors.find(current) == m_actors.end()) { return false; } if (obj.getID() != m_actors[current]->getID()) { return false; // Mismatch } // Check if the square is occupied if (m_actors.find(next) != m_actors.end()) { return false; } // Check if the square is passable terrain // Consult the tilemap auto row = next.getY(); auto col = next.getX(); bool ret = true; // Check for on/off the map if (next.getX() < 0 || next.getX() >= m_tilemap->getWidth()) { cout << "Off left/right edge" << cout; // DEBUG return false; } if (next.getY() < 0 || next.getY() >= m_tilemap->getHeight()) { cout << "Off bottom/edge edge" << cout; // DEBUG return false; } switch ((*m_tilemap)[row][col].getType()) { case TileType::None: case TileType::Blank: case TileType::Water: case TileType::Building: ret = false; break; case TileType::Terrain: case TileType::Door: case TileType::Indoor: case TileType::Ladder: case TileType::Staircase: ret = true; break; default: ret = false; } // Check the move distance auto deltaX = current.getX() - next.getX(); auto deltaY = current.getY() - next.getY(); auto absdiff = abs(deltaX) + abs(deltaY); if (absdiff != 1) { cout << "Abs move fail" << endl; ret = false; } // Incorporate game state into decision ret = ret && !m_gameState->levelOver() && m_gameState->canMove(); return ret; }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); double bdx = BALL_DX; double bdy = BALL_DY(BALL_DX); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // keep playing until game over GObject collisionObject; waitForClick(); while (lives > 0 && bricks > 0) { GEvent eMouse = getNextEvent(MOUSE_EVENT); if (eMouse != NULL) { if (getEventType(eMouse) == MOUSE_MOVED) { int x = getX(eMouse) - getWidth(paddle) / 2; setLocation(paddle, x, PADDLE_Y); } } move(ball,bdx,bdy); if((getX(ball) + getWidth(ball) >= WIDTH || getX(ball) <= 0)) { bdx *= -1; } else if(getY(ball) <= 0) { bdy *= -1; } else if ((getY(ball) + getHeight(ball) >= HEIGHT)) { lives--; setLocation(ball, (WIDTH/2) - RADIUS, (HEIGHT / 2) - RADIUS); setLocation(paddle,PADDLE_X, PADDLE_Y); bdx = BALL_DX; bdy = BALL_DY(BALL_DX); waitForClick(); } collisionObject = detectCollision(window, ball); if (collisionObject != NULL && strcmp(getType(collisionObject), "GRect") == 0) { bdy *= -1; if (collisionObject != paddle) { removeGWindow(window, collisionObject); bricks--; points++; updateScoreboard(window, label, points); printf("bricks: %d points: %d\n", bricks, points); } } } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
Point Point::operator*(const float &f) { Point result(getX() * f, getY() * f, getZ() * f); return result; }
Vector2 operator/(const float scaler) const { return Vector2(getX() / scaler, getY() / scaler); }
// Other methods void Particle::update(){ // main method that controls all necessary movement // attraction and repulsion float dy = (ofGetWindowHeight() - ofGetMouseY()) - getY(); float dx = ofGetMouseX() - getX(); if (getAttract() && !getRepel()){ float desired = atan2(dy,dx); float angdiff = desired-getAngle(); if ((angdiff > 0 && abs(angdiff) <= PI) || (angdiff < 0 && abs(angdiff) > PI)){ setAngle(getAngle() + getAlpha()); } else if ((angdiff > 0 && abs(angdiff)>PI) || (angdiff < 0 && abs(angdiff) <= PI)){ setAngle(getAngle() - getAlpha()); } // if (desired+getAlpha()>getAngle() && desired-getAlpha()<getAngle()){ // setSpeed(getSpeed()+getFlow()); // } // else { // if (getSpeed()>ORBITAL_FACTOR*getFlow()){ // setSpeed(getSpeed()-getFlow()); // } // } } else if (getRepel() && !getAttract() && sqrt(pow(dy,2) + pow(dx,2)) <= BARRIER){ float desired = atan2(dy,dx) > 0 ? atan2(dy,dx) - PI : atan2(dy,dx) + PI; float angdiff = desired - getAngle(); if ((angdiff > 0 && abs(angdiff) <= PI) || (angdiff < 0 && abs(angdiff) > PI)){ setAngle(getAngle() + getAlpha()); } else if ((angdiff > 0 && abs(angdiff) > PI) || (angdiff < 0 && abs(angdiff) <= PI)){ setAngle(getAngle() - getAlpha()); } // if (desired+getAlpha()>getAngle() && desired-getAlpha()<getAngle()){ // setSpeed(getSpeed()+getFlow()); // } // else { // if (getSpeed()>ORBITAL_FACTOR*getFlow()){ // setSpeed(getSpeed()-getFlow()); // } // } } else if (getAttract() && getRepel()){ if (getSpeed() > 0){ setSpeed(getSpeed() - getFlow()); } } // life if (getAlive()){ setAngle(getAngle() + ofRandomf() * getAlpha()); setSpeed(getSpeed() + ofRandomf() * getFlow()); setRadius(getRadius() + ofRandomf() * RADIUS_NOISE); } // bounds if (getX() > ofGetWindowWidth() - getRadius() || getX() < getRadius()){ setAngle(-getAngle() + PI); } if (getY() > ofGetWindowHeight() - getRadius() || getY() < getRadius()){ setAngle(-getAngle()); } // position + motion position += velocity; // color float r = getAttract() && getRepel() ? getColor().r + 1 : (getSpeed()/MAX_SPEED) * 255; float g = getAttract() ? getColor().g + 1 : (getY()/ofGetWindowHeight()) * 255; float b = getRepel() ? getColor().b + 1 : (1-getY()/ofGetWindowHeight()) * 255; setColor(r,g,b); }
float angle() const { return ::atan2(getY(), getX()); }
void Particle::draw(){ graphic.setColor(getColor().r,getColor().g,getColor().b); graphic.circle(getX(),ofGetWindowHeight() - getY(),getRadius()); }
float dot(const Vector2& rhs) const { return (getX() * rhs.getX()) + (getY() * rhs.getY()); }
void PluginWindow::moved() { owner->properties.set ("uiLastX", getX()); owner->properties.set ("uiLastY", getY()); }
Vector2 negated() const { return Vector2(-getX(), -getY()); }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // wait for click before starting waitForClick(); // ball speed double xspeed =drand48() + 1.5; double yspeed = 2.5; // keep playing game until these conditions are met while (lives > 0 && bricks > 0) { // Scoreboard updateScoreboard(window, label, points); // move ball move(ball, xspeed, yspeed); pause(10); // listen for mouse event GEvent event = getNextEvent(MOUSE_EVENT); // validation for an event if (event != NULL) { if (getEventType(event) == MOUSE_MOVED) { // make sure paddle follows the mouse double x = getX(event) - getWidth(paddle) / 2; double y = HEIGHT - 100; setLocation(paddle, x, y); } } GObject object = detectCollision(window, ball); if (object != NULL) { // when ball strucks the paddle if (object == paddle) { yspeed = -yspeed; } // keep track of stats else if (strcmp(getType(object), "GRect") == 0) { removeGWindow(window, object); yspeed = -yspeed; points = points + 1; bricks = bricks - 1; } } // when ball hits left wall if (getX(ball) <= 0) { xspeed = -xspeed; } // when the ball hits the top wall. if (getY(ball) <= 0) { yspeed = -yspeed; } // when ball hits the right wall if (getX(ball) + getWidth(ball) >= 400) { xspeed = -xspeed; } // bottom wall below paddle if (getY(ball) + getHeight(ball) >= 600) { lives = lives - 1; // reset setLocation(ball, WIDTH / 2 - RADIUS, HEIGHT / 2 + RADIUS); setLocation(paddle, 160, 500); waitForClick(); } // end of game, winner! if (points == 25) { GLabel win = newGLabel("Good Job! You win!"); setFont(win, "SansSerif-36"); setColor(win, "BLUE"); setLocation(win, 15, 300); add(window, win); } } waitForClick(); closeGWindow(window); return 0; }
/*public*/ void HCoordinate::getCoordinate(Coordinate& ret) const { ret = Coordinate(static_cast<double>(getX()), static_cast<double>(getY())); }
void Protester::doSomething(){ if(!isAlive()) return; ticksSincePTurn++; if(!isActive){ if(getX() == 60 && getY() == 60) setDead(); Direction dir = getWorld()->determineFirstMoveToExit(this, getX(), getY()); if(dir != none) setDirection(dir); move(getDirection()); return; } if(shoutWait != 0) shoutWait--; FrackMan* a = getWorld()->findNearbyFrackMan(this, 4); if(a && getWorld()->isFacingFrackMan(this)){ if(shoutWait == 0){ getWorld()->playSound(SOUND_PROTESTER_YELL); a->annoy(2); shoutWait = 15; return; } } if(getWorld()->lineOfSightToFrackMan(this) != none){ setDirection(getWorld()->lineOfSightToFrackMan(this)); move(getDirection()); numMovesInCurDir = 0; return; } numMovesInCurDir--; if(numMovesInCurDir <= 0){ for(;;){ int dir = randInt(0, 3); if(dir == 0 && getWorld()->canActorMove(this, up)) { setDirection(up); break; } else if(dir == 1 && getWorld()->canActorMove(this, down)) { setDirection(down); break; } else if(dir == 2 && getWorld()->canActorMove(this, left)) { setDirection(left); break; } else if(dir == 3 && getWorld()->canActorMove(this, right)) { setDirection(right); break; } } numMovesInCurDir = randInt(8, 60); } else if ( ticksSincePTurn >= 200 ) { Direction dir = getDirection(); if(wasPTurn(dir, up)){ if(getWorld()->canActorMove(this, up)) setDirection(up); } if(wasPTurn(dir, down)){ if(getWorld()->canActorMove(this, down)){ if(getDirection() == up){ if(randInt(0,1) == 1)setDirection(down); } else { setDirection(down); } } } if(wasPTurn(dir, left)){ if(getWorld()->canActorMove(this, left)) setDirection(left); } if(wasPTurn(dir, right)){ if(getWorld()->canActorMove(this, right)){ if(getDirection() == left){ if(randInt(0,1) == 1)setDirection(right); } else { setDirection(right); } } } if(dir != getDirection()){ ticksSincePTurn = 0; numMovesInCurDir = randInt(8, 60); } } if(getWorld()->canActorMove(this, getDirection())) { move(getDirection()); } else numMovesInCurDir = 0; }
int main(int argc, char* argv[]) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // add ball to window add(window, ball); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // add paddle to window add(window, paddle); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // add label to window add(window, label); // declare laser GRect laser = NULL; // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // ball velocity double velocity_x = drand48() * 2 + 3; double velocity_y = drand48() * 2 + 3; bool ballMove = false; // GOD mode on bool God = false; if (argc == 2) { if (strcmp(argv[1], "GOD") == 0) { God = true; } } // keep playing until game over while (lives > 0 && bricks > 0) { // check for mouse event GEvent event = getNextEvent(MOUSE_EVENT); // when clicked, ball starts to move if (event != NULL) { // if the event was moved if (getEventType(event) == MOUSE_CLICKED) { ballMove = true; } } // ball movement if (ballMove == true) { move(ball, velocity_x, velocity_y); // when ball hits the left edge if (getX(ball) <= 0) { velocity_x *= -1; } // when ball hits the right edge else if (getX(ball) + getWidth(ball) >= getWidth(window)) { velocity_x *= -1; } // when ball hits the top edge else if (getY(ball) <= 0) { velocity_y *= -1; } // when ball hit the bottom edge else if (getY(ball) >= getHeight(window)) { lives -= 1; ballMove = false; setLocation(ball, WIDTH / 2, HEIGHT / 2); } pause(10); } // if God mode is on, paddle x-position follows ball if (God == true) { double y = getY(paddle); setLocation(paddle, getX(ball) + RADIUS - PADDLEWIDTH / 2.0, y); } // else if God mode is off, paddle follow mouse movement else { // if we heard one if (event != NULL) { // if the event was moved if (getEventType(event) == MOUSE_MOVED && ballMove == true) { double x = getX(event) - PADDLEWIDTH / 2; double y = getY(paddle); // ensure paddle doesn't go out of window if (getX(event) <= 0 + PADDLEWIDTH / 2) { setLocation(paddle, 0, y); } else if (getX(event)>= getWidth(window) - PADDLEWIDTH / 2) { setLocation(paddle, getWidth(window) - PADDLEWIDTH, y); } else { setLocation(paddle, x, y); } } } } // during gameplay, when mouse is clicked, shoot laser if (event != NULL) { if (ballMove == true && getEventType(event) == MOUSE_CLICKED && laser == NULL) { // instantiate laser laser = newGRect(getX(paddle) + PADDLEWIDTH / 2 - LASERWIDTH / 2, getY(paddle) - LASERHEIGHT, LASERWIDTH, LASERHEIGHT); setColor(laser, "RED"); setFilled(laser, true); add(window, laser); } } // if laser exists if (laser != NULL) { // detect collision of laser with object GObject object2 = detectCollision2(window, laser); if (object2 != NULL) { // if laser hits brick if (strcmp(getType(object2), "GRect") == 0 && object2 != paddle) { // remove laser and brick hit GObject laserObj = getGObjectAt(window, getX(laser), getY(laser)); removeGWindow(window, laserObj); laser = NULL; removeGWindow(window, object2); // bricks higher in the game’s grid are worth more points than are bricks lower in the game’s grid int brickheight = (100 - GAP * (ROWS + 1)) / ROWS; for (int k = 0; k < ROWS; k++) { if (getY(object2) == 50 + (GAP * (k + 1)) + (brickheight * k)) { points += ROWS - k; break; } } updateScoreboard(window, label, points); // decrease paddle width bricks -= 1; setSize(paddle, PADDLEWIDTH - PADDLEWIDTH * 2 / 4.0 * (((ROWS * COLS) - bricks) / (float)(ROWS * COLS)), PADDLEHEIGHT); // increase velocity of ball velocity_x += 0.1; velocity_y += 0.1; } // else if laser hits ball else if (object2 == ball) { GObject laserObj = getGObjectAt(window, getX(laser), getY(laser)); removeGWindow(window, laserObj); laser = NULL; break; } // else if laser over top edge else if (getY(laser) + LASERHEIGHT >= 0) { GObject laserObj = getGObjectAt(window, getX(laser), getY(laser)); removeGWindow(window, laserObj); laser = NULL; } } else { move(laser, 0, -velocity_laser); } } // detect collision of ball with object GObject object = detectCollision(window, ball); if (object != NULL) { // if ball collide with paddle if (object == paddle) { velocity_y *= -1; } // if ball collide with GRect object other than paddle (i.e. bricks) else if (strcmp(getType(object), "GRect") == 0) { velocity_y *= -1; removeGWindow(window, object); // bricks higher in the game’s grid are worth more points than are bricks lower in the game’s grid int brickheight = (100 - GAP * (ROWS + 1)) / ROWS; for (int k = 0; k < ROWS; k++) { if (getY(object) == 50 + (GAP * (k + 1)) + (brickheight * k)) { points += ROWS - k; break; } } updateScoreboard(window, label, points); // paddle width decrease bricks -= 1; setSize(paddle, PADDLEWIDTH - PADDLEWIDTH * 2 / 4.0 * (((ROWS * COLS) - bricks) / (float)(ROWS * COLS)), PADDLEHEIGHT); // velocity of ball increases velocity_x += 0.1; velocity_y += 0.1; } } // when no more live or all bricks are broken if (lives == 0 || bricks == 0) { break; } } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
void FrackMan::doSomething(){ if(!isAlive()) return; int key; if (getWorld()->getKey(key)){ switch(key){ case KEY_PRESS_UP: if(getDirection() == up) { move(up); } else setDirection(up); break; case KEY_PRESS_DOWN: if(getDirection() == down) { move(down); } else setDirection(down); break; case KEY_PRESS_LEFT: if(getDirection() == left) { move(left); } else setDirection(left); break; case KEY_PRESS_RIGHT: if(getDirection() == right) { move(right); } else setDirection(right); break; case KEY_PRESS_ESCAPE: setDead(); break; case KEY_PRESS_SPACE: { if(m_uWater != 0){ getWorld()->playSound(SOUND_PLAYER_SQUIRT); Actor* a = new Squirt(getWorld(), getX(), getY(), getDirection()); getWorld()->addActor(a); m_uWater--; } break; } case KEY_PRESS_TAB: { if(m_nNuggets != 0){ m_nNuggets--; Actor* a = new GoldNugget(getWorld(), getX(), getY(), true); getWorld()->addActor(a); } break; } case 'z': case 'Z': { if(m_nCharges !=0){ getWorld()->playSound(SOUND_SONAR); getWorld()->revealAllNearbyObjects(getX(), getY(), 12); m_nCharges--; } break; } } getWorld()->updateFrackmanMap(getX(), getY()); if(getWorld()->displaceDirt(getX(), getY())) getWorld()->playSound(SOUND_DIG); } }
void Paddle::reset() { rect.setPosition(getX(), INIT_Y); }
Vector2 operator-(const Vector2& rhs) const { return Vector2(getX() - rhs.getX(), getY() - rhs.getY()); }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; double paddleLength = 60; double x, y, velocityx ,velocityy; velocityx = velocityy = 2; // keep playing until game over while (lives > 0 && bricks > 0) { // Check beyong paddle position if (getY(ball) + getWidth(ball) >= getHeight(window)) { // if ball does not touch the bat but bottom of window //creates new ball object and deduct lives removeGWindow(window, ball); freeGObject(ball); lives--; if (lives <= 0) { break; } initBall(window); waitForClick(); } // Move paddle along with mouse GEvent event = getNextEvent(MOUSE_EVENT); if (event != NULL) { if (getEventType(event) == MOUSE_MOVED) { double x = getX(event); // Paddle should not go outside of the window if(x + getWidth(paddle) > getWidth(window)) x = (getWidth(window)- getWidth(paddle)); double y = getHeight(window) - 50 - getHeight(paddle); setLocation(paddle, x,y); } } // Accelerate x cordinates of the ball i.e. left and right if (getX(ball) + getWidth(ball) >= getWidth(window)) { //printf("Inseide if getX(ball) event\n"); velocityx = -velocityx; } else if (getX(ball) <= 0) { //printf("Else if getX(ball) event\n"); velocityx = -velocityx; } //printf("After if getX(ball) event\n"); // Acceleration control check for top of the window if (getY(ball) <= 0) { velocityy = -velocityy; } // Acceleration control if ball collided with paddle or brick GObject object = detectCollision (window, ball); if (object!= NULL) { // Acceleration control if ball collided with paddle if (object == paddle) { velocityy = -velocityy; move(ball, velocityx, velocityy); } // Acceleration, ScoreBoard, brick control if ball collided with brick if (strcmp(getType(object), "GRect") == 0 && getY(ball) < HEIGHT / 2) { //ScoreBoard points ++; updateScoreboard(window, label, points); //bricks removeGWindow(window,object); bricks = bricks - 1; velocityy = -velocityy; if (bricks < 0) { break; } } } move(ball, velocityx, velocityy); // pause (8); } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
void Box::render() { // faces are rendered counter clockwise, starting 'top-right'. float mcolor[] = { 1.0f, 0.0f, 0.0f, 1.0f }; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mcolor); // front faces are counter-clockwise glFrontFace(GL_CCW); glBegin(GL_QUADS); // 'front' face Vertex a(getX() + getWidth(), getY() + getHeight(), getZ()); Vertex b(getX(), getY() + getHeight(), getZ()); Vertex n1 = Vertex::calcNormal(a,b); n1.normalize(); glNormal3f(n1.x, n1.y, n1.z); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ()); glVertex3f(getX(), getY() + getHeight(), getZ()); glVertex3f(getX(), getY(), getZ()); glVertex3f(getX() + getWidth(), getY(), getZ()); // 'back' face glNormal3f(0.0f, 0.0f, -1.0f); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX(), getY(), getZ() + m_depth); glVertex3f(getX() + getWidth(), getY(), getZ() + m_depth); // 'top' face glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX(), getY() + getHeight(), getZ()); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ()); // 'bottom' face glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(getX() + getWidth(), getY(), getZ() + m_depth); glVertex3f(getX(), getY(), getZ() + m_depth); glVertex3f(getX(), getY(), getZ()); glVertex3f(getX() + getWidth(), getY(), getZ()); // 'left' face glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(getX(), getY(), getZ()); glVertex3f(getX(), getY() + getHeight(), getZ()); glVertex3f(getX(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX(), getY(), getZ() + m_depth); // 'right' face glNormal3f(1.0f, 0.0f, 0.0f); glVertex3f(getX() + getWidth(), getY(), getZ()); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ()); glVertex3f(getX() + getWidth(), getY() + getHeight(), getZ() + m_depth); glVertex3f(getX() + getWidth(), getY(), getZ() + m_depth); glEnd(); }