Bug phenomenon: Figure I
Figure I, Code analysis
Snake.prototype.move=function(food,map) {//the head moves first, Switch( This. Direction) { Case"Right": This. body[0].x +=1; Break; Case"Left": This. body[0].x-=1; Break; Case"Top": This. BODY[0].Y-=1; Break; Case"Bottom": This. BODY[0].Y +=1; Break; } varI= This. body.length-1; for(i;i>0;i--){ This. body[i].x= This. body[i-1].x;//section X coordinates = = first section X coordinate This. body[i].y= This. body[i-1].y; }
Results of Run/ ** /
Figure II is correct
Figure II Code Analysis
Snake.prototype.move=function(food,map) {varI= This. body.length-1; for(i;i>0;i--){ This. body[i].x= This. body[i-1].x;//section X coordinates = = first section X coordinate This. body[i].y= This. body[i-1].y; } //head back Move Switch( This. Direction) { Case"Right": This. body[0].x +=1; Break; Case"Left": This. body[0].x-=1; Break; Case"Top": This. BODY[0].Y-=1; Break; Case"Bottom": This. BODY[0].Y +=1; Break; } /*Run result this.body=[{x:3,y:2,color: "Red"}, {x:2,y:2,color: "Orange"}, {x: 1,y:2,color: "Orange"}]; this.body=[0 {x:4,y:2,color: "Red"}, 1 {x:3,y:2,color: "Orange"}, 2 {x:2,y:2,color: "Oran GE "}]; */
Conclusion:
1,bug logic errors cause, remind oneself especially in learning things, clear logic realization principle, where data is produced, where is used.
2, debugging ability to get great exercise, this time from the discovery of the phenomenon, to keep trying behind the reasons, finally began to write the test code in the file, and finally find out exactly where the error, and experienced 1 hours or so.
3, the error is not terrible, terrible is not make mistakes, a little problem. Experience, not this time, make a mistake, and conquer it then you will.
A reflection on the bug of JavaScript imitating snake