【问题标题】:Snake game: How to increase the length of a snake body based on the amount of food eaten?蛇游戏:如何根据吃的食物量增加蛇身的长度?
【发布时间】:2019-01-06 21:42:09
【问题描述】:

我正在尝试重现蛇吃食物并且身体增加 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

我希望蛇尾跟随蛇头,并根据吃的食物量增加基础。

【问题讨论】:

  • 在你想要什么和你拥有什么之间需要做很多工作。似乎最好的方法是模拟你的蛇已经吃掉了 5 株植物。如果是这样的话,那条蛇在所有 5 块中是如何移动的?然后,如果蛇吃植物,只需在尾巴原来的位置生成一段。为此,您可能需要跟踪蛇的尾巴以及尾巴的先前 xcor/ycor。

标签: netlogo


【解决方案1】:

解决此类问题的一种简便方法是使用链接来连接组成蛇的段。

下面的代码应该可以帮助您入门。我不会向您介绍整个过程,但一般方法是使用定向链接将每个“尾部”段连接到前面的段。

当添加一个新的尾段时,我们递归地寻找一个还没有“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

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2022-11-19
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多