Skip to content

Commit

Permalink
feat: 身体跟随蛇头移动
Browse files Browse the repository at this point in the history
  • Loading branch information
tianqing617 committed Nov 17, 2021
1 parent 8d826ab commit c3075e8
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/GameControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@ export default class GameControl {

return window.setInterval(() => {
// console.log('setInterval', this)
// !!!蛇爬动
this.run();
}, this.getSpeed());
}

keydownHandler(event: KeyboardEvent): void {
console.log(event);
// if ()
this.direction = event.key;
// this.run();
}
Expand Down
15 changes: 12 additions & 3 deletions src/components/playGround/PlayGround.vue
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,26 @@ export default {
border: 2px solid #000;
position: relative;
}
#snake {
> b {
// 蛇头和蛇身样式
::v-deep(#snake) {
> b, i {
width: 10px;
height: 10px;
background-color: #000;
border: 1px solid #BDD4AB;
position: absolute;
}
> b {
top: 110px;
left: 30px;
position: absolute;
}
> i {
background-color: red;
top: 1px;
left: 1px;
}
}
#food {
height: 10px;
width: 10px;
Expand Down
19 changes: 18 additions & 1 deletion src/components/playGround/Snake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default class Snake {

set headPointer(pointer: Pointer) {
// console.log('pointer', pointer);
// 身体跟随蛇头移动
this.moveBody();

// 设置蛇头
// console.log('headPointer', pointer);
this.headEl.style.top = pointer.y + 'px';
Expand All @@ -37,7 +40,21 @@ export default class Snake {

// 移动蛇身
moveBody(): void {
//
/**
* 将后边的身体设置为 前面身体的位置
* 第4节 = 第3节的位置
* 第3节 = 第2节的位置
* 第2节 = 蛇头的位置
*/
for (let i = this.bodyListEl.length - 1; i > 0; i--) {
const currentEl = this.bodyListEl.item(i) as HTMLElement;
const previousEl = this.bodyListEl.item(i - 1) as HTMLElement;

if (currentEl && previousEl) {
currentEl.style.left = previousEl.offsetLeft + 'px';
currentEl.style.top = previousEl.offsetTop + 'px';
}
}
}

// 检查是否撞到自己
Expand Down

0 comments on commit c3075e8

Please sign in to comment.