Parallel but not really parallel. Moving game characters. Coroutines in Lua.
Archive - Originally posted on "The Horse's Mouth" - 2011-08-17 20:47:43 - Graham EllisVirtual World game programming involves moving many characters - both player controlled and automatic - in parallel. The movements of each character depend - to a greater or lesser extent - on the prior movements of the character, and of the other charcaters and the resultant position and condition that they're left in. Can you imagine what a complex coding task that could be?

I've written coroutine demos before (see [here]), but I wrote a more specific virtual world example during the Lua Programming course I was presenting today.
Scenario. Jane has a 10 metre start over 10 Johns in a chase. Jane moves forward a randon amount each second - somewhere between 0 and 0.9 metres. Each of the Johns moves forward between 0 and 1 metres. Simulate the chase.
Let's start by defining the movement routine for Jane:
function movejane()
local covered = 10.0
while true do
local stepsize = math.random()*0.9
covered = covered + stepsize
at = covered
target = at
coroutine.yield()
end
end
and the movement routine for each John:
function movejohn()
local covered = 0
while true do
local stepsize = math.random()
covered = covered + stepsize
at = covered
if at > target then
winner = 1
else
winner = 0
end
coroutine.yield()
end
end
Note that there are local variables for each of the different characters, and global variables which are used to maintain the global statuses and generally visible data.
We'll then set up a table of characters:
characters = {coroutine.create(movejane)}
for k = 1, 10 do
crh = coroutine.create(movejohn)
characters[#characters+1] = crh
end
and ... finally ... code a loop to run our simulation for 200 seconds:
for seconds = 1, 200 do
for person = 1,#characters do
coroutine.resume(characters[person])
io.write (string.format("%6.2f ",at))
if winner == 1 then break end
end
if winner == 1 then
io.write(" WONHER\n")
break
end
io.write("\n")
end
Let's see how that runs ...
munchkin:laug11 grahamellis$ lua charmoves
10.63 0.58 0.94 0.74 0.37 0.94 0.15 0.26 0.85 0.96 0.07
11.46 0.79 1.77 1.31 1.05 1.69 0.95 0.38 1.49 1.94 0.09
11.91 1.40 1.95 1.97 1.27 2.05 1.64 0.46 2.18 2.64 0.22
12.34 1.88 2.05 2.65 1.37 2.35 2.48 0.49 2.33 3.43 1.20
12.41 2.04 2.09 3.41 1.57 3.00 3.08 1.33 2.71 4.40 1.67
12.43 2.45 2.47 4.18 1.85 3.55 3.19 1.89 3.11 5.03 2.12
12.80 2.86 2.47 5.13 2.36 3.72 3.34 1.98 4.07 5.12 3.12
[etc]
31.31 24.97 23.33 28.77 24.51 22.43 26.29 23.60 27.76 25.90 27.72
31.57 25.86 23.66 29.50 25.46 22.58 26.37 23.81 28.26 26.46 28.51
31.95 26.28 24.09 30.01 25.76 22.85 26.88 24.62 29.23 26.68 29.41
32.14 26.70 24.44 30.78 26.39 23.07 27.70 25.29 30.00 27.19 30.24
32.51 27.22 25.09 31.59 27.21 23.48 28.12 26.24 30.50 27.71 30.58
32.94 27.45 25.18 32.53 27.98 23.81 28.59 26.55 31.31 28.32 31.11
33.17 28.45 25.33 33.52 WONHER
munchkin:laug11 grahamellis$
Full source code [here].