Ejemplo n.º 1
0
void Snake::moveSnake()
{
   switch (last)
   {
      case Key_Up: move(up); break;
      case Key_Left: move(left);  break;
      case Key_Right: move(right); break;
      case Key_Down: move(down);  break;
    }
    detectCrash();
}
Ejemplo n.º 2
0
void Snake::move(SpriteDB::Direction newdir)
{
    // Add a new segment in the same place as the head
    QAnimatedPixmapItem* sprite = new QAnimatedPixmapItem(SpriteDB::spriteCache(), scene );
    sprite->setFrame(SpriteDB::snakeBody(currentdir, newdir));
    sprite->setPos(snakelist.first()->x(), snakelist.first()->y() );
    sprite->show();
    snakelist.insert(1, sprite);

    // Move the head to its new position
    int x = 0;
    int y = 0;
    switch (newdir) {
        case SpriteDB::right: x = SpriteDB::tileSize(); break;
        case SpriteDB::left: x = -SpriteDB::tileSize(); break;
        case SpriteDB::down: y = SpriteDB::tileSize(); break;
        case SpriteDB::up: y = -SpriteDB::tileSize(); break;
    }
    snakelist.first()->moveBy(x, y);

    // Make sure the head is pointing in the right direction
    if (currentdir != newdir) {
        currentdir = newdir;
        snakelist.first()->setFrame(SpriteDB::snakeHead(currentdir));
    }

    // Move the tail along unless the snake is growing
    if (grow <= 0) {
        // Remove the tail (deleting it automatically removes it from the scene).
        delete snakelist.takeLast();

        // Change the new last segment to the tail image with correct direction
        QAnimatedPixmapItem * last = snakelist.last();
        QAnimatedPixmapItem * prev = snakelist[snakelist.size()-2];

        SpriteDB::Direction taildir;
        if ( prev->x() == last->x() ) {  //vertical
            taildir = prev->y() > last->y() ? SpriteDB::down : SpriteDB::up;
        } else {  //horizontal
            taildir = prev->x() > last->x() ? SpriteDB::left : SpriteDB::right;
        }

        snakelist.last()->setFrame(SpriteDB::snakeTail(taildir));
    }
    else
        grow--;

    // Redraw the scene
    scene->update();

    // Decide if the snake collided with a wall or mouse
    detectCrash();
}