This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Brian87's profile picture

need help with loop

Started by Brian87, 20 February 2014 - 02:23 PM
Brian87 #1
Posted 20 February 2014 - 03:23 PM
Hello!
I'm trying to make the turtle detect if there is a mob, then kill it. Since "turtle.detect()" doesn't work I've tried some other alternatives. The only thing that doesn't work is when it turns left or right it attacks only one time, but I want it to detect if there is a mob to kill, then sleep for a second and then check if there is a mob again. Can someone please help me? :)/>

The code looks like this:

local function attack()
if not turtle.forward() then
  while turtle.attack() do
   while turtle.attack() do end
   sleep(1)
  end
  turtle.forward()
end
end

local function ifAttack()
turtle.attack()
while turtle.attack() do
  while turtle.attack() do end
  sleep(3)
end
end

local function moveForward()
for i = 1,2 do
  turtle.forward()
  attack()
  turtle.turnLeft()
  ifAttack()
  turtle.turnRight()
  turtle.turnRight()
  ifAttack()
  turtle.turnLeft()
end
turtle.turnRight()
turtle.turnRight()
end

local function moveBack()
turtle.forward()
attack()
turtle.forward()
attack()
end

while true do
moveForward()
moveBack()
moveForward()
moveBack()
end
Bomb Bloke #2
Posted 20 February 2014 - 07:45 PM
Odd, I'd expect "while turtle.attack() do end" to attack over and over until there's nothing left to bash.

While turtles can't detect mobs (short of by attacking and checking the result), they can detect redstone signals, such as those produced by pressure plates with mobs standing on them.
Brian87 #3
Posted 20 February 2014 - 08:02 PM
The problem is this part of the code I think:


local function ifAttack()
turtle.attack()
while turtle.attack() do
  while turtle.attack() do end
  sleep(3)
end
end

I want it to turn left and then attack, and if there is anything to attack, it attacks until the mob is dead, and then sleeps and checks again. But what it does now is just attack once :(/>
Edited on 20 February 2014 - 07:03 PM
Bomb Bloke #4
Posted 21 February 2014 - 07:31 AM
My only thought is that the turtle's first attack is knocking the mobs back a far enough that it's unable to strike them a second time. The turtle should simply keep on striking until it finds nothing in range.

By the way, the function should act in a very similar manner to what you've got if it were written as just:

local function ifAttack()
  while turtle.attack() do
    sleep(3)
  end
end