在做任何东西之前,你会觉得没有一点点头绪,从而因为胆怯而惊恐放弃,但在开始之后,你会慢慢找到思路,然后一步一步克服困难。
先给出完整代码,然后再拆分说明
贪吃蛇小游戏完整代码
一、little-game.component.ts
import {
Component, OnInit } from '@angular/core';
import {
EventManager } from'@angular/platform-browser'
@Component({
selector: 'app-little-game',
templateUrl: './little-game.component.html',
styleUrls: ['./little-game.component.css']
})
export class LittleGameComponent implements OnInit {
start:boolean=false;//控制着游戏的开始
isShow:boolean=true;//控制着小蛇的显示
foodColors:string[]=['yellow','green','orange','purple','blue','pink','cyan'];
foodColor:string;
foodX:number;//食物的位置left
foodY:number;//食物的位置top
snake=[{
top:120,left:60},{
top:120,left:30},{
top:120,left:0}];//用于初始化小蛇
intervalId:any;//该变量作为时间函数的id,可用于停止游戏
speed:number=600;//决定小蛇移动的速度,会随着小蛇的长度改变,设置不同的速度
direction:string="right";//移动方向
moveX:number=60;//小蛇蛇头的位置
moveY:number=120;
maxClientX:number=document.documentElement.clientWidth;//可见屏幕宽度
maxClientY:number=document.documentElement.clientHeight;
startGame(){
//开始游戏按钮触发函数
this.start=true;
this.isShow=false;
this.intervalId=setInterval(()=>{
this.snakeMove();
},this.speed);
}
snakeMove(){
//小蛇移动函数
var snake=document.querySelectorAll(".snake");
switch(this.direction){
//更改头snake_head移动的方向,每次移动30px
case 'left':{
this.moveX-=30;break;}
case 'top':{
this.moveY-=30;break;}
case 'right':{
this.moveX+=30;break;}
case 'bottom':{
this.moveY+=30;break;}
}
for(var i=snake.length-1;i>0;i--){
//使snake_body移动
snake[i].setAttribute('style',`${
snake[i-1].getAttribute('style')}`);
}
snake[0].setAttribute('style',`top:${
this.moveY}px ;left:${
this.moveX}px;background-color:${
this.foodColors[Math.round(Math.random()*6)]}`);
this.rightPosition();
this.eatFood();
this.speedUp(snake.length);
}
setDirection(keyCode){
//改变小蛇移动方向函数
switch(keyCode){
case 37:{
if(this.direction!="right"){
//如果小蛇正在向右移动,则按<--不起作用
this.direction="left";
}
break