肖强的博客 肖强的博客
Home
Guide
Web Document
  • Plugins
  • Case
  • Animation
Components
  • Categories
  • Tags
  • Archives
Website Tools

xiaoQiang

因为爱所以爱
Home
Guide
Web Document
  • Plugins
  • Case
  • Animation
Components
  • Categories
  • Tags
  • Archives
Website Tools
  • 案例
    • Gluttonous Snake
    • Verification Code
    • Star sky
    • gobang
    • drawing
    • china map
  • views
xiaoQiang
2021-09-29

gluttonousSnake

gluttonousSnake

贪吃蛇 方向键进行移动

<template>
  <div>
    <canvas
      ref="snakeCanvas"
      width="400"
      height="400"
      style="background: Black; display: block; margin: 20px auto"
    ></canvas>
  </div>
</template>
<script>
export default {
  name: 'gluttonousSnake',
  data() {
    return {
      sn: [42, 41],
      dz: 43,
      fx: 1,
      n: null,
    }
  },
  mounted() {
    window.addEventListener('keydown', e => {
      this.fx =
        this.sn[1] - this.sn[0] ==
        (this.n = [-1, -20, 1, 20][e.keyCode - 37] || this.fx)
          ? this.fx
          : this.n
      e.preventDefault()
    })
    this.snakeRender()
  },
  methods: {
    snakeRender() {
      const ctx = this.$refs.snakeCanvas.getContext('2d')
      this.sn.unshift((this.n = this.sn[0] + this.fx))
      if (
        this.sn.indexOf(this.n, 1) > 0 ||
        this.n < 0 ||
        this.n > 399 ||
        (this.fx == 1 && this.n % 20 == 0) ||
        (this.fx == -1 && this.n % 20 == 19)
      )
        return alert('GAME OVER')
      this.draw(this.n, 'Lime', ctx)
      if (this.n == this.dz) {
        while (this.sn.indexOf((this.dz = ~~(Math.random() * 400))) >= 0);
        this.draw(this.dz, 'Yellow', ctx)
      } else this.draw(this.sn.pop(), 'Black', ctx)
      setTimeout(this.snakeRender, 300)
    },
    draw(t, c, ctx) {
      ctx.fillStyle = c
      ctx.fillRect((t % 20) * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18)
    },
  },
}
</script>
#case
上次更新: 2021-10-10 23:28:19
Verification Code

Verification Code→

最近更新
01
drag
12-22
02
入场/出场05
10-16
03
入场/出场04
10-16
更多文章>
icon组件不能用
时间左侧 © 2021-2021 时间右侧
冀公网安备 13108202000744号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
欢迎来到我的家
Back