I've always wondered how to make a snake game, but I never tried so this morning, seeing as I could either study for a chemistry exam I have tomorrow or try to make my first MX 2004 flash game, considering I got the trial version yesterday. Naturally I chose the game, heres the code(Game link at bottom) I just wanna know what you guys think of my coding rather then the game because this really only the second or third time I've ever used any Object Oriented type stuff and I want to know how I can improve:
File(Snake.as):
First Frame of Flash:Code:class Snake extends MovieClip{
private var snkinst:Number;
private var xv,yv,cspeed,ym,xm:Number;
public function Snake(passedinst:Number){
snkinst = passedinst;
cspeed = 10;
}
public function moveNext(){
if(snkinst == 0){
_root["s"+snkinst].px = _root["s"+snkinst]._x;
_root["s"+snkinst].py = _root["s"+snkinst]._y;
_root["s"+snkinst]._x += cspeed*xv;
_root["s"+snkinst]._y += cspeed*yv;
}else{
xm = _root["s"+(snkinst-1)].px;
ym = _root["s"+(snkinst-1)].py;
_root["s"+snkinst].px = _root["s"+snkinst]._x;
_root["s"+snkinst].py = _root["s"+snkinst]._y;
_root["s"+snkinst]._x = xm;
_root["s"+snkinst]._y = ym;
}
}
public function keyCheck(){
if(Key.isDown(Key.UP) && yv != 1){
yv = -1;
xv = 0;
}
if(Key.isDown(Key.LEFT) && xv != 1){
xv = -1;
yv = 0;
}
if(Key.isDown(Key.RIGHT) && xv != -1){
xv = 1;
yv = 0;
}
if(Key.isDown(Key.DOWN) && yv != -1){
yv = 1;
xv = 0;
}
}
}
The other frame is just the gameover one no real code in there so I left it out. You can play the flash here: My First Snake Game (Start the game and play it using any of the arrow keys)Code:var mySnake:Snake = new Snake(0);
var csc:Number = 1;
var pscore:Number = 0;
_root.onLoad = function(){
_root.ball._x = random(490);
_root.ball._y = random(490);
}
_root.onEnterFrame = function(){
if(_root.s0._x > 500 or _root.s0._x < 0 or _root.s0._y > 500 or _root.s0._y < 0){
for(r=0;r<=csc;r++){
_root["s"+r].removeMovieClip();
}
gotoAndStop(2);
}
for(r=3;r<=csc;r++){
if(_root["s"+r].hitTest(_root.s0)){
for(q=0;q<=csc;q++){
_root["s"+q].removeMovieClip();
}
gotoAndStop(2);
}
}
if(_root.s0.hitTest(_root.ball)){
_root.ball._x = random(490);
_root.ball._y = random(490);
_root.attachMovie("snake","s"+csc,csc+130,"snake");
_root["s"+csc]._x = _root["s"+csc-1]._x;
_root["s"+csc]._y = _root["s"+csc-1]._y + 10;
set("sn"+csc, new Snake(csc));
pscore++;
csc++;
}
mySnake.keyCheck();
mySnake.moveNext();
tscore = "Score: " + pscore;
for(i=1;i<=csc;i++){
_root["sn"+i].moveNext();
}
}
stop();