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

Turtle that moves 20 spaces and turns if theres a block infront

Started by zeldafan99, 10 May 2012 - 07:29 PM
zeldafan99 #1
Posted 10 May 2012 - 09:29 PM
its safe to say i have no idea what im doing, ive managed to get it to move 20 spaces, and turn if theres a block infront, but how do i allow it to move the rest of its spaces once it turns?

this is the code i have so far


x = 20
y = 0
z = 0

while x > 0 do

turtle.forward()
x = x-1
z = z+1
end

if turtle.detect() then
turtle.turnRight()
y = y+1
end

print (" i moved "..z.." spaces")
print (" and turned "..y.." times")
MysticT #2
Posted 10 May 2012 - 10:16 PM
It would be better to do the check in the loop, and a for loop it's better with counters:

local steps = 20 -- number of blocks to move

local function move()
  while not turtle.forward() do
    turtle.turnRight()
  end
end

for i = 1, steps do
  move()
end
This would make the turtle move the amount of blocks you want, and turn if it can't go forward.
LipJ #3
Posted 10 May 2012 - 10:43 PM
Or for curtain of twenty:

local spaces = 20

For I = 1, 20 do
If turtle.detect() do 
turtle.turnRight()
Turtle.forward()
Else
Turtle.forward()
End
End
MysticT #4
Posted 10 May 2012 - 11:17 PM
Or for curtain of twenty:

local spaces = 20

For I = 1, 20 do
If turtle.detect() do
turtle.turnRight()
Turtle.forward()
Else
Turtle.forward()
End
End
But it won't always make the number of moves you want. If there's a block in front and on the right of the turtle, it wont move, but it will keep going anyway. It's better to check the return value of turtle.forward.
PixelToast #5
Posted 10 May 2012 - 11:57 PM
fixed your code :3 happy coding!


spaces=20
turns=0
for I = 1, spaces do
while turtle.detect() do while not turtle.turnRight() do end turns=turns+1 end
while not turtle.forward() do end
end
print("turned "..turns.." times")
the common problem with turtle.forward() is that sometimes it is called while it is still going forward, this ensures that turtle.forward() will return true at least 20 times
EDIT: tested it in game, works fine :)/>/>
EDIT: made my own code for my turtle that just sits there in my warehouse

while true do
  while turtle.detect() or math.random(1,10)==1 do
    if math.random(0,1)==1 then
	  while not(turtle.turnRight()) or turtle.detect() do end
    else
	  while not(turtle.turnLeft()) or turtle.detect() do end
    end
  end
  while not turtle.forward() do end
end