void UpdateController::moveSnake(Snake &snake) { switch (input) { case KEY_LEFT: snake.movex(-1); break; case KEY_RIGHT: snake.movex(1); break; case KEY_UP: snake.movey(-1); break; case KEY_DOWN: snake.movey(1); break; default: snake.movex(1); } for ( auto iter = coins.begin(), endPtr = coins.end() ; iter != endPtr ; ++iter ) { if (snake.headLiesOn(iter->getxy())) { snake.grow(iter->getvalue()); coinMutex.lock(); *iter = Coin(getFreeCoord()); coinMutex.unlock(); break; } } auto head = snake.getHead(); if (snake.bitItself() || !map.contains(head) || snakeWallCollision()) { stop(); } }
void ItemFactory::addFood() { //check if the food still exist if (m_pFood) return; //check the empty grid Snake* snake = dynamic_cast<Snake*>(getParent()->getChildByTag(eID_Snake)); if (!snake) return; int left = m_pSnakeMap->getMovableNumbers() - snake->getLength(); //no empty grids left, you win if (left <= 0) return; //set the food index int index = (int)(rand() % left + 1); auto mapIndex = m_pSnakeMap->getEmptyGridIndex(index); //create food model m_pFood = Food::create(); this->addChild(m_pFood, 1, eID_Food); m_pFood->setPosition(VisibleRect::getVisibleRect().origin + VisibleRect::getHalfGridVec() + VisibleRect::getGridLength()*mapIndex); m_pFood->setIndex(mapIndex); //set the grid type m_pSnakeMap->setGridType(mapIndex, eType_Food); }
int main() { sf::RenderWindow Window; Window.create(sf::VideoMode(900, 900), "Snake", sf::Style::Default); Window.setKeyRepeatEnabled(false); Snake *snake = new Snake(); while (Window.isOpen()) { sf::Event Event; while (Window.pollEvent(Event)) { switch (Event.type) { case(sf::Event::Closed): Window.close(); break; } } Window.clear(); snake->Draw(Window); Window.display(); } system("pause"); return 0; }
//-------------------------------------------------------------- void ofApp::draw(){ ofDrawBitmapString(state, 100, 100); ofDrawBitmapString(snake.countEatFood, 800, 100); if (state == S_BEGIN) { ofDrawBitmapString(ofToString(state) + " Start game", 300, 300); } if (state == S_GAME) { ofDrawBitmapString(ofToString(state) + " Game in state game", 300, 300); showSnake(); showFood(); } if (state == S_WIN) { ofDrawBitmapString(ofToString(state) + " Game win!", 300, 300); snake.rePosition(); } if (state == S_LOOSE) { ofDrawBitmapString(ofToString(state) + " Game loose!", 300, 300); snake.rePosition(); } }
int NCurseGui::printGame(const Snake& snake, const Apple & apple) { std::deque<std::pair<int, int> > s = snake.getSnake(); std::deque<std::pair<int, int> >::const_iterator it = s.begin(); int apple_color; if (apple.getAge() <= apple.getBonusAge()) apple_color = 4; else if (apple.getAge() > apple.getRottenAge()) apple_color = 5; else apple_color = 1; wborder(_win, '|', '|', '_', '_', ' ', ' ', '|', '|'); wattron(_win, COLOR_PAIR(3)); mvwprintw(_win, it->first + 1, it->second * 2 + 1, " "); wattroff(_win, COLOR_PAIR(3)); while (++it != s.end()) { wattron(_win, COLOR_PAIR(2)); mvwprintw(_win, it->first + 1, it->second * 2 + 1, " "); wattroff(_win, COLOR_PAIR(2)); } wattron(_win, COLOR_PAIR(apple_color)); mvwprintw(_win, apple.getApple().first + 1, apple.getApple().second * 2 + 1, " "); wattroff(_win, COLOR_PAIR(apple_color)); std::pair<size_t, size_t> lastLink = snake.getLastChain(); mvwprintw(_win, lastLink.first + 1, lastLink.second * 2 + 1, lastLink.first + 1 == _height ? "__" : " "); wrefresh(_win); return 0; }
void draw2Buffer_1p() { // Fill in new buffer prevBuffer = curBuffer; for (UINT i = 0; i < Buffer::width; i++) { curBuffer[i][0] = '#'; } for (UINT i = 0; i < Buffer::width; i++) { for (UINT j = 1; j < Buffer::height - 1; j++) { if (i == 0 || i == Buffer::width - 1) curBuffer[i][j] = '#'; else if (sk1.isHeadLoc(i, j)) curBuffer[i][j] = 'O'; else if (fr.isHere(i, j)) curBuffer[i][j] = '*'; else if (sk1.isTailLoc(i, j)) curBuffer[i][j] = 'o'; else curBuffer[i][j] = ' '; } } for (UINT i = 0; i < Buffer::width; i++) { curBuffer[i][Buffer::height - 1] = '#'; } // Write to screen hScreen->updateScreen(curBuffer, prevBuffer); // Update score hScreen->updateScore(sk1.score); }
Snake* Snake::Load(const char* file_name) { Snake* snake = NULL; ifstream file(file_name); if (!file) return NULL; int dir, x, y; // Create a new snake snake = new Snake; snake->head = snake->tail = NULL; // Load moving direction file >> dir; snake->dir = (Direction) dir; // Load the body while(file >> x >> y) { Node* node = new Node; node->x = x; node->y = y; node->prevNode = NULL; mvaddch(node->y, node->x, '*'); if (snake->head == NULL) { snake->head = node; snake->tail = node; } else { snake->InsertAtHead(node); } } return snake; }
int Food::hasBeenEatenBy(Snake& aSnake) { switch(type) { case addPoint: return 1; break; case minusThreePoints: return -3; break; case increaseSpeed: if (aSnake.speed > 1) { aSnake.speed--; } break; case decreaseSpeed: aSnake.speed++; break; case increaseLength: aSnake.growSnake(); break; case decreaseLength: aSnake.shrinkSnake(); break; } return 1; }
/* Method is responsible for runtime checks: - Collision detection - Food eaten - Drawing Return(true) -> GameOver Return(false)-> Keep running */ bool GameController::performGameRuntimeChecks(CInputManager &inputManager, unsigned long &score, CollisionDetector &collisionDetector, DrawEngine drawEngine, int key, Snake &snake, vector<Cell> &foodList, FoodProvider &foodProvider, Cell lastCell) { //If collision detected if(collisionDetector.collisionDetected(snake)) { char message[] = "GAME OVER! <Press any key>"; drawEngine.showMessage(message); inputManager.GetNextKeyWait(&key); return true; } //Food eaten else if(collisionDetector.foodEaten(snake, foodList)) { //Setting new score score += snake.getCells().size()*2; //Draw score drawEngine.updateScore(score); //Add cell snake.addCell(); //Recieving new foodList vector<Cell> &list = foodProvider.provideFood(snake, drawEngine.getWindownWidth(), drawEngine.getMenuBorderHeight()); foodList = list; } //Draw snake drawEngine.drawSnake(snake, lastCell); //Draw food drawEngine.drawFood(foodList); return false; }
int main(int argc,char *argv) { system("color 4A"); Snake sna; Apple fd; fd=product_food(fd);; //сно╥я╜╩╥ while(1) { if(sna.is_dead()) { system("cls"); GameOver(); break; } if(sna.is_eat(fd)) { fd=product_food(fd); } if(sna.is_win()) { break; } sna.Move(); } return 0; }
void playon(Board & terminal) { while((command = getch()) != 'q' && !gameover) { clear(); //mvprintw(y,x,"☺"); Ekans.move(command); Ekans.display(); gameover = Ekans.check_coord(terminal); pidgey.check(Ekans, terminal); refresh(); } if(gameover) { clear(); //center end screen mvprintw(ystart-2,xstart-6, "GAMEOVER"); mvprintw(ystart ,xstart-6, "Score: %d ", Ekans.score); refresh(); sleep(2); } }
/* Controla la entrada de teclado del usuario ****************************************************************************************/ bool Input(Snake &serpiente){ bool result = false; SDL_Event event; if( SDL_PollEvent( &event ) ){ //Recogemos el evento if( event.type == SDL_KEYDOWN ){ //Se ha pulsado una tecla switch( event.key.keysym.sym ){ case SDLK_ESCAPE: result = true; //Escape: Salimos del programa break; case SDLK_UP: serpiente.SetVelocidad(-1, 0); break; case SDLK_DOWN: serpiente.SetVelocidad(1, 0); break; case SDLK_LEFT: serpiente.SetVelocidad(0, -1); break; case SDLK_RIGHT: serpiente.SetVelocidad(0, 1); break; } }else if( event.type == SDL_QUIT ){ //Se quita el programa result = true; } } return result; }
//-------------------------------------------------------------- void ofApp::keyPressed(int key){ if (key == OF_KEY_UP) { snake.setMove(0, -1); } if (key == OF_KEY_DOWN) { snake.setMove(0, 1); } if (key == OF_KEY_LEFT) { snake.setMove(-1, 0); } if (key == OF_KEY_RIGHT) { snake.setMove(1, 0); } if (key == ' ') { SetState(S_BEGIN); } if (key == 'g') { SetState(S_GAME); } if (key == 'w' && state == S_GAME) { SetState(S_WIN); } if (key == 'l' && state == S_GAME) { SetState(S_LOOSE); } }
void update(void){ f.update(); razer_convert_keycode_to_pos(keys_history[0],&pos); if (last_pos.x!=pos.x || last_pos.y!=pos.y){ last_pos.x=pos.x; last_pos.y=pos.y; //cout <<"key pos = "<<(pos).x<<","<<(pos).y<<endl; } direction_t d=LEFT; if(pos.x == 16 && pos.y == 4) d=UP; else if(pos.x == 16 && pos.y == 5) d=DOWN; else if(pos.x == 15 && pos.y == 5) d=LEFT; else if(pos.x == 17 && pos.y == 5) d=RIGHT; s.move(d); g.update(); s.update(); razer_update_keys(chroma,chroma->keys); usleep(400000); Cord sc = s.getFront(); Cord fc = g.getPosition(); if(sc.x==fc.x && sc.y==fc.y){ Food tmp = Food(); s.grow(); s.grow(); g = tmp; } razer_update(chroma); razer_frame_limiter(chroma,13); }
void Game::loop(void) { Map *map; Snake *snake; map = this->getMap(); snake = new Snake(map->getWidth() / 2, map->getHeight() / 2); map->setSnake(snake); while (!this->_shouldExit) { Time::update(); /* events */ this->_handleInputs(this->_dlib->getInput()); /* update */ if (!this->_isPaused) this->update(); /* refresh display */ this->_dlib->draw(map); Time::sleep(200 - snake->getSpeed() * 10); } this->_dlib->close(); printf("Final score: %d\n", this->_score); }
void GameLayer::AddBody(){ head->setPosition(food->getPosition()); Snake* node = Snake::create(); node->setNode(Sprite::create("Snake.png")); node->setPosition(lastbodyposi); body.pushBack(node); this->addChild(node); }
int main(int argc, const char *argv[]) { Snake snakeGame; snakeGame.start(); return 0; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); Snake w; w.show(); return a.exec(); }
void Game::_handleCollisions(void) { Snake *snake; Map *map; map = getMap(); snake = map->getSnake(); // with the edge if (snake->_head->getX() < 0 || snake->_head->getX() > map->getWidth() - 1 || snake->_head->getY() < 0 || snake->_head->getY() > map->getHeight() - 1) { printf("GAME OVER! (bang the wall)\n"); this->_shouldExit = TRUE; return ; } // with himself for (std::list<GameEntity *>::iterator it = snake->_body.begin(); it != snake->_body.end(); it++) { if ((*it)->getX() == snake->_head->getX() && (*it)->getY() == snake->_head->getY()) { printf("GAME OVER! (the head in the ass)\n"); this->_shouldExit = TRUE; return ; } } // with an obstacle std::list<GameEntity *> obst = map->getObstacles(); for (std::list<GameEntity *>::iterator it = obst.begin(); it != obst.end(); it++) { if ((*it)->getX() == snake->_head->getX() && (*it)->getY() == snake->_head->getY()) { printf("GAME OVER! (hit an obstacle)\n"); this->_shouldExit = TRUE; return ; } } // with an apple std::list<GameEntity *> apple = map->getApple(); for (std::list<GameEntity *>::iterator it = apple.begin(); it != apple.end(); it++) { if ((*it)->getX() == snake->_head->getX() && (*it)->getY() == snake->_head->getY()) { snake->setState("grow"); snake->upSpeed(1); (*it)->setPosition(-1, -1); this->_score++; map->setScore(this->_score); } } // with bonus GameEntity * bonus = map->getBonus(); if (bonus->getX() == snake->_head->getX() && bonus->getY() == snake->_head->getY()) { snake->setState("grow"); bonus->setPosition(-1, -1); this->_score += 10; map->setScore(this->_score); } }
void Controller::updateWorld(unsigned char *snakeData) { struct retrievedServerData *playerData = (struct retrievedServerData*) snakeData; playerOne.setPlayerPosX(playerData->info[0]); playerOne.setPlayerPosY(playerData->info[1]); playerTwo.setPlayerPosX(playerData->info[2]); playerTwo.setPlayerPosY(playerData->info[3]); }
void Lib_Ncurses::draw_snake() const { Snake *snake = this->_game->getSnake(); for (std::list<SnakeElement *>::const_iterator it = snake->getList().begin(); it != snake->getList().end(); ++it) { const int *pos = (*it)->getPos(); move(pos[1], pos[0]); addch('X'); } }
void Apple::Collide(Snake& snake) { snake.Grow(); m_used = true; if (snake.IsPlayer()) { Game& game = GetGame(); game.GetStatus().AppleEaten(); game.GetSfxManager().GetSound("apple")->Play(); } }
int main() { char randomCharacter; Snake SNAKE; SNAKE.Start(); cin >> randomCharacter; return 0; }
Snake* Snake::create(const NPCData& data, ESnakeType type) { Snake* npc = new Snake(); if (npc && npc->init(data, type)) { return (Snake*)npc->autorelease(); } CC_SAFE_DELETE(npc); return npc; }
void ItemFactory::addDoor() { //check if the doors exist if (m_pDoors.first != nullptr || m_pDoors.second != nullptr) return; //check the empty grid Snake* snake = m_pSnakeMap->getSnake(); if (!snake) return; int left = m_pSnakeMap->getMovableNumbers() - snake->getLength(); //no empty grids left if (left <= 0) return; //set the door index int index = (int)(rand() % left + 1); auto mapIndex = m_pSnakeMap->getEmptyGridIndex(index); //create door model m_pDoors.first = Door::create(); this->addChild(m_pDoors.first, 1, eID_Door1); m_pDoors.first->setPosition(VisibleRect::getVisibleRect().origin + VisibleRect::getHalfGridVec() + VisibleRect::getGridLength()*mapIndex); m_pDoors.first->setIndex(mapIndex); //set the door transfer direction auto transferDir = randomDirection(); m_pDoors.first->setTransferDirection(transferDir); //actual door direction is opposite to transfer direction m_pDoors.first->setRotation(arcByDirection(oppositeDirection(transferDir))); //set the grid type m_pSnakeMap->setGridType(mapIndex, eType_Door); //create the second door index = (int)(rand() % left + 1); mapIndex = m_pSnakeMap->getEmptyGridIndex(index); m_pDoors.second = Door::create(); this->addChild(m_pDoors.second, 1, eID_Door2); m_pDoors.second->setPosition(VisibleRect::getVisibleRect().origin + VisibleRect::getHalfGridVec() + VisibleRect::getGridLength()*mapIndex); m_pDoors.second->setIndex(mapIndex); transferDir = randomDirection(); m_pDoors.second->setTransferDirection(transferDir); m_pDoors.second->setRotation(arcByDirection(oppositeDirection(transferDir))); m_pSnakeMap->setGridType(mapIndex, eType_Door); //connect the two doors m_pDoors.first->setOtherDoor(m_pDoors.second); m_pDoors.second->setOtherDoor(m_pDoors.first); }
unsigned char Controller::getSnakeY(char port[10]) { if(strcmp(port, "9000")==0) { return playerTwo.getPosY(); }else if(strcmp(port, "9001")==0) { return playerTwo.getPosY(); }else{ return 0; } }
bool GameLayer::ifCollideBody(Point pos){ bool value = false; Snake* node; for (int i =0; i<body.size(); i++) { node = body.at(i); Point nodepos = node->getPosition(); if(nodepos==pos){ value = true; } } return value; }
int main(){ initCanvas("Snake", gridsep*npts, gridsep*npts); Snake s; while(true){ XEvent event; if(checkEvent(event) && keyPressEvent(event)){ char c = charFromEvent(event); s.move(c); } else s.move('\0'); // NULL = continue to move in previous direction. wait(0.1); } }
void Game::Update() { float frametime = 1.0f / 10.f; if (_elapsed.asSeconds() >= frametime) { _snake.Tick(); _world.Update(_snake); _elapsed -= sf::seconds(frametime); if (_snake.HasLost()) { _textBox.Add("Game Over! Final Score: " + std::to_string(_snake.GetScore())); _snake.ResetToStart(); } } }
bool Pit::moveSnakes() { for (int k = 0; k < m_nSnakes; k++) { Snake* sp = m_snakes[k]; sp->move(); if (sp->row() == m_player->row() && sp->col() == m_player->col()) m_player->setDead(); } // return true if the player is still alive, false otherwise return ! m_player->isDead(); }