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

Making the monsters spawn at a random location

Started by nikolay04, 02 October 2016 - 06:03 PM
nikolay04 #1
Posted 02 October 2016 - 08:03 PM
So i want my monsters to spawn at diffrent locations each time i kill them. here is the code P.S this is my first game ever, what do you think

local x = 20
local y = 10
local w, h = term.getSize(w, h)
local sX, sY = x, y + 0 + 1
local monsterX = math.random(1,20)
local monsterY = math.random(1,10)
local points = 0
local kM = false

while true do
  term.clear()
  term.setCursorPos(x,y)
  print"@"
  term.setCursorPos(sX,sY)
  print("-|--")
  term.setCursorPos(50,1)
  print(points)

  if monsterX ~= sX and monsterY ~= sY then
term.setCursorPos(monsterX, monsterY)
print"!"
end

  local hendelse, tast = os.pullEvent("key")
 


   if monsterX == sX and monsterY == sY then
    local monsterX = math.random(1,20)
local monsterY = math.random(1,10)
term.setCursorPos(monsterX, monsterY)
term.clear()
points = points + 1
local kM = true
end
 
  if tast == keys.q then
    break
  end
 
  if x == monsterX and y == monsterY then
    term.setCursorPos(30,10)
    print"You died"
    sleep(.5)
    break
  end
 
 
  if tast == keys.right then
    x =  x + 1
    sX = sX + 1
  end
 
  if tast == keys.left then
    x = x - 1
    sX = sX - 1
  end
 
  if tast == keys.up then
    y = y - 1
    sY = sY + -1
  end
 
  if tast == keys.down then
    y = y + 1
    sY = sY + 1
  end
 
  if tast == keys.space then
  
  end
end
xsamxx #2
Posted 03 October 2016 - 01:31 AM
The only issue here is that when you assign a new location to the monster you include the local keyword, which tells lua to define a new variable (or overwrite one) and only make that variable available in the current block scope, in this case, since the initial definition of monsterX and Y are in a higher scope than that logic, the new random position gets discarded after it exits the if block. To fix this, just remove the local before monsterX and Y on lines 29 and 30.