JS、HTML5实现贪吃蛇小游戏

本文介绍如何使用JavaScript和HTML5创建贪吃蛇小游戏,从完整代码到逐步解析,涵盖游戏框架建立、小蛇移动、键盘监听、食物生成、碰撞检测等关键步骤。
摘要由CSDN通过智能技术生成

在做任何东西之前,你会觉得没有一点点头绪,从而因为胆怯而惊恐放弃,但在开始之后,你会慢慢找到思路,然后一步一步克服困难。

先给出完整代码,然后再拆分说明

贪吃蛇小游戏完整代码

一、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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值