贪吃蛇游戏:如何根据食用的食物量增加蛇的长度body?

Snake game: How to increase the length of a snake body based on the amount of food eaten?

我正在尝试重新创建蛇吃食物并且 body 增加 1 个单位的贪吃蛇游戏。然而,我已经多次尝试增加 body 的长度,但没有任何事情按照我想要的方式进行。我试着创造另一种海龟,叫做 "tails",然后在蛇后面孵化它。但是由于我使用的是 ticks,所以尾巴生成得非常快,并且不会产生 snake-like 效果。相反,尾巴聚集在蛇身后的一个补丁上。

我试过给蛇所在的斑块上色,但我不知道如何根据所吃的食物只给一定数量的斑块上色,然后逐渐添加。所以现在,我尝试使用品种尾巴,但它不会创建蛇形。

这是我的代码:

breed [snakes snake]
breed [foods food]
breed [tails tail]
tails-own [age]

to game2-setup

  create-snakes 1 [
  set shape "snake"
  set color green
  ]

create-foods 10 [
setxy random-xcor random-ycor
if [pcolor] of patch-here != black [move-to one-of patches with [pcolor = 
black]]
set shape "plant"
set color red]
end

to game2-go

;moves the snake
ask snakes [
if ticks mod 350 = 0 [fd 1]
]

;to kill snake if it bumps into a wall/itself
ask snakes
[if [pcolor] of patch-ahead 1 != black [
user-message "Game over" ]
]

 ;if the snake and food is on the same patch the food is eaten
 ask patches [ if any? snakes-here and any? foods-here
 [ask foods-here [die]
 set points points + 1
 set energy energy + 1
 ]]

 ;grows the tail of the turtle based on the amount of food eaten
 ask tails
 [set age age + 1
 if age = 10 [die]
 ]

 ;regrows the food
 if count foods < 10
 [create-foods 1
 [setxy random-xcor random-ycor
 if [pcolor] of patch-here != black [move-to one-of patches with [pcolor = 
 black]]
 set shape "plant"
 set color red]
 ]
 tick
 end

我希望蛇尾跟在黑鱼之后,并根据吃的食物量增加。

解决此类问题的一种简便方法是使用 links 连接构成蛇的线段。

下面的代码应该可以帮助您入门。我不会向您介绍整个过程,但一般方法是使用定向 links.

将每个 "tail" 段连接到前面的段

添加新的尾段时,我们递归地寻找还没有 "in" link 的段,从那里孵化一个新的尾段,并将其连接到其父段.

移动时,每个尾部片段都面向它所连接的片段,并在其一个片段内移动。请注意我们如何使用 foreach sort tails 而不是仅 ask tails 来确保片段按其创建顺序移动。

breed [snakes snake]
breed [tails tail]
breed [foods food]

to setup
  clear-all
  create-snakes 1 [ set color green ]
  ask n-of 10 patches [ sprout-foods 1 [ set shape "plant" ] ]
  reset-ticks
end

to go
  ask snakes [
    right random 45
    left random 45
    forward 1
    if any? foods-here [
      ask one-of foods-here [ die ]
      add-tail
    ]
  ]
  foreach sort tails [ t ->
    ask t [
      let segment-ahead one-of out-link-neighbors
      face segment-ahead
      forward max list 0 (distance segment-ahead - 1)
    ]
  ]
  tick
end

to add-tail
  ifelse any? in-link-neighbors [
    ask one-of in-link-neighbors [ add-tail ]
  ] [
    hatch-tails 1 [ create-link-to myself ]
  ]
end