Jump to content




Making the monsters spawn at a random location


1 reply to this topic

#1 nikolay04

  • Members
  • 9 posts

Posted 02 October 2016 - 07: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


#2 xsamxx

  • New Members
  • 1 posts

Posted 03 October 2016 - 12: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users