#include "snakebody.h"
#include <QDebug>
#include <QSettings>
SnakeBody::SnakeBody(QObject *parent) : QObject(parent)
{
body << Node(0,0) << Node(1,0) << Node(2,0);
}
SnakeBody::~SnakeBody()
{
// QSettings settings = QSettings("HCHEDU","QtSnake");
// settings.setValue("snake_body_length",body.count());
// for(int i=0;i<body.count();i++)
// settings.setValue("node"+i,QVariant(body[i]));
}
void SnakeBody::update(QPainter &p)
{
for(int i=0;i<body.count();i++){
QPen pen;
pen.setColor(body[i].penColor());
pen.setWidth(2);
p.setPen(pen);
QBrush brush;
brush.setColor(body[i].brushColor());
brush.setStyle(Qt::SolidPattern);
p.setBrush(brush);
//p.drawRect(body[i].rect());
p.drawPixmap(body[i].rect(),body[i].pixmap());
}
}
void SnakeBody::move(int curDir,bool touchFoodFlag)
{
Node head = body.first();
//qDebug() << head.x() << head.y() << curDir;
switch (curDir){
case RIGHT:
head.setX(body.last().x()+1);
head.setY(body.last().y());
break;
case LEFT:
head.setX(body.last().x()-1);
head.setY(body.last().y());
break;
case DOWN:
head.setY(body.last().y()+1);
head.setX(body.last().x());
break;
case UP:
head.setY(body.last().y()-1);
head.setX(body.last().x());
break;
}
if(!touchFoodFlag)
body.takeFirst();
body.append(head);
}
bool SnakeBody::isTouchFood(int curDir, SnakeFood &food)
{
Node head = body.first();
//qDebug() << head.x() << head.y() << curDir;
switch (curDir){
case RIGHT:
head.setX(body.last().x()+1);
head.setY(body.last().y());
break;
case LEFT:
head.setX(body.last().x()-1);
head.setY(body.last().y());
break;
case DOWN:
head.setY(body.last().y()+1);
head.setX(body.last().x());
break;
case UP:
head.setY(body.last().y()-1);
head.setX(body.last().x());
break;
}
if(head.x() == food.x() && head.y() == food.y())
return true;
else
return false;
}