ZIYI CHEN ml17z4c 201214999

Dependencies:   mbed

Eng/Eng.cpp

Committer:
ziyi11
Date:
2019-05-09
Revision:
14:60c31d25d895
Parent:
13:08bdb4cffacd

File content as of revision 14:60c31d25d895:

#include "Eng.h"

Eng::Eng()
{

}

Eng::~Eng()
{

}

void Eng::init()
{
    dSnake.init(5,10);    //she de chu shi zuo biao
    _noodles.init(20,7);
    _gameOver = false;

}



void Eng::userinput(Gamepad &pad)
{
    _d = pad.get_direction();
}

void Eng::draw(N5110 &lcd)
{
    lcd.drawRect(0,0,84,48,FILL_TRANSPARENT);
//
    for (int i = 0; i < 84; i++) {
        for (int j = 0; j < 48; j++) {
            if (snake1[j][i] != 0) {
                lcd.drawRect((2 * j) + 2,(2 * i) + 2,2,2,FILL_BLACK);
            }
        }
    }
}

void Eng::score(N5110 &lcd)
{

    lcd.clear();
    lcd.printString("Score ",0,0);
    char buffer[14];
    int _score = (dSnake.getLength() - 5);

    sprintf(buffer,"%3d",_score);
    lcd.printString(buffer,0,1);



    lcd.refresh();

    wait(5.0);
}

void Eng::update(Gamepad &pad)
{

    memset(snake1, 0, sizeof(snake1));
    dSnake.update(_d);

    dead();

    snake1[_noodles.xcoordinate()][_noodles.ycoordinate()] = 2;

    if (checkFood()) {
        
        pad.tone(1000.0,0.1);
   
        growSnake();

        bool empty = false;

        while (!empty) {

            _noodles.random();

            if ( snake1[_noodles.xcoordinate()][_noodles.ycoordinate()] == 0) {

                empty = true;
            }
        }
    }
}

void Eng::dead()
{

    int _l =dSnake.getLength();

    for (int i = 0; i < _l; i++) {

        if (dSnake.xcoordinate(i) > 40) {
            _gameOver = true;
        } else if( dSnake.xcoordinate(i) < 0) {
            _gameOver = true;
        } else if (dSnake.ycoordinate(i) > 22 ) {
            _gameOver = true;
        } else if(dSnake.ycoordinate(i) < 0) {
            _gameOver = true;
        }

        if (snake1[dSnake.xcoordinate(i)][dSnake.ycoordinate(i)] != 1) {
            snake1[dSnake.xcoordinate(i)][dSnake.ycoordinate(i)] = 1;
        } else {
            _gameOver = true;
        }
    }
}

bool Eng::checkFood()
{
    if (snake1[dSnake.xcoordinate(0)][dSnake.ycoordinate(0)] == 2) {
        return true;
    } else {
        return false;
    }
}

void Eng::growSnake()
{
    if (dSnake.getLength()<4032) {

        dSnake.grow();

    }
}

float Eng::getScore()
{
    return _score;
}


bool Eng::getGameOver()
{
    return _gameOver;
}