March 24th, 2016

[KISSCODE] Let's make SNAKE Pt. 4

by Adhi.Lius

Hi happy another #KISSCodeThursday. Now continuing from our part 3, we are going for the fruit before the snake body.

To add a fruit is quite easy. We can just randomly get a position and then put a code for the fruit there.

//get a random empty position

protected Vector2 GetRandomPosition(){

int posX = Random.Range (1, 39);

int posY = Random.Range (1, 29);

while(snakeArray[posX,posY] != 0){

posX = Random.Range (1, 39);

posY = Random.Range (1, 29);

}

return new Vector2 (posX, posY);

}

public GameObject fruitPrefab;

//put fruit

protected void PutNewFruit(){

Vector2 fruitPos = GetRandomPosition ();

snakeArray [(int)fruitPos.x, (int)fruitPos.y] = 3;

}

//recount the array

protected void RefreshSnakeArray(){

for (int i = 1; i < 39; i++) {

for (int j = 1; j < 29; j++) {

if (snakeArray[i,j] != 3){ // don't delete fruit

snakeArray [i, j] = 0;

}

}

}

snakeArray [(int)cSnakePos.x, (int)cSnakePos.y] = 2;

}

//draw anything besides the wall

protected void RedrawScene(){

CleanScene ();

for (int i = 1;i<39;i++){

for (int j = 1; j < 29; j++) {

int code = snakeArray [i, j];

if (code != 0) {

float POS_X = FIRST_POS_X + (i * BLOCK_SiZE);

float POS_Y = FIRST_POS_Y - (j * BLOCK_SiZE);

if (code == 2) { // snake body

GameObject nSnakeBody = Instantiate (snakePrefab);

nSnakeBody.transform.parent = stageHolder;

nSnakeBody.transform.position = new Vector2 (POS_X, POS_Y);

drawnObject.Add (nSnakeBody);

} else if (code == 3) { // fruit

Debug.Log ("draw fruit");

GameObject nFruit = Instantiate (fruitPrefab);

nFruit.transform.parent = stageHolder;

nFruit.transform.position = new Vector2 (POS_X, POS_Y);

drawnObject.Add (nFruit);

}

}

}

}

}

// Use this for initialization

void Start () {

InitWalls ();

InitSnake ();

DrawScene ();

PutNewFruit ();

RedrawScene ();

}

Don't forget to create and then assign the fruit prefab in the editor. Now hit run and you will get the fruit.

Now what we need is the logic to make the fruit get eaten and then respawned again.

//recount the array

protected void RefreshSnakeArray(){

for (int i = 1; i < 39; i++) {

for (int j = 1; j < 29; j++) {

if (snakeArray[i,j] != 3){ // don't delete fruit

snakeArray [i, j] = 0;

}

}

}

CheckSnakeHitAnything ();

snakeArray [(int)cSnakePos.x, (int)cSnakePos.y] = 2;

}

protected int cScore = 0;

protected void CheckSnakeHitAnything(){

int code = snakeArray [(int)cSnakePos.x, (int)cSnakePos.y];

if (code != 0){ // hit something

if (code == 3){ // eat fruit

PutNewFruit ();

cScore++;

}

}

}

Hit the run and you will see the fruit keeps on being created whenever eaten.

Okay that's it for today. I am sorry for this short post, but I am quite busy and late lately. There is going to be a Jakarta Unity VR Roadshow on Friday so gotta need to prepare for it. So see you and if you are going there, see you there :)

Originally Posted in: blog.sinergistudio.com

Comments (0)