我正在尝试重新制作蛇游戏,在该游戏中蛇吃食物并且身体增加1个单位。但是我已经尝试了多次以增加身体的长度,但是没有任何事情像我想要的那样起作用。我试图创造出另一种称为“尾巴”的海龟并在蛇后孵化。但是由于我使用的是壁虱,所以尾巴的繁殖速度非常快,而且不会产生类似蛇的效果。取而代之的是,尾巴在蛇后面的一个斑块上聚集在一起。
我曾尝试为蛇身上的补丁着色,但我不知道如何仅根据所吃的食物着色一定数量的补丁并逐渐添加到上面。所以现在,我尝试使用种尾,但它不会产生蛇形。
这是我的代码:
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
我希望蛇的尾巴在蛇头后面尾随,并根据食用的食物量增加。
答案 0 :(得分:4)
解决此类问题的一种简便方法是使用链接来连接形成蛇的线段。
下面的代码应该可以帮助您入门。我不会逐步介绍整个过程,但是通常的方法是使用定向链接将每个“尾部”段连接到前面的段。
在添加新的尾段时,我们以递归的方式查找尚无“ in”链接的线段,在此处填充新的尾段,并将其连接到其父级。
移动时,每个尾段都面向与其连接的段,并在其一个拼块内移动。请注意,我们如何使用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