-
Notifications
You must be signed in to change notification settings - Fork 0
/
conversation.lua
384 lines (329 loc) · 11.7 KB
/
conversation.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
-- ##################################################################
-- # Package: conversation.
-- # This package contains code for generating and displaying
-- # questions/statements and answers.
-- ##################################################################
local P = {}
conversation = P
-- ##################################################################
-- # Imports
-- ##################################################################
require "input"
require "timer"
local love = love
local table = table
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local next = next
local string = string
local input = input
local timer = timer
local type = type
local math = math
local os = os
local print = print
setfenv(1, P)
-- ##################################################################
-- # Paths
-- ##################################################################
local topicsPath = "resources/text/topics.txt"
local fillerPath = "resources/text/filler.txt"
local backgroundImage = love.graphics
.newImage("resources/images/background.png")
local rightAnswer = love.audio.newSource("resources/sound/Collect_Point_00.mp3",
"static")
local wrongAnswer = love.audio.newSource("resources/sound/Hit_02.mp3", "static")
-- ##################################################################
-- # Constants
-- ##################################################################
local topicRate = 2
local coolDownPeriod = 0.5
local startingTime = 2
local gameOverTime = 3
-- ##################################################################
-- # Variables
-- ##################################################################
local fillerAnswers = {}
local topicStrings = {}
local questionTimerPercent = 100
local attentionPercent = 100
-- ##################################################################
-- # Table for holding a conversation topic.
-- ##################################################################
local Topic = {}
function Topic:new(comment, answer, wrongAnswer1, wrongAnswer2, fillerAnswer,
fillerAllowed)
local o = {
comment = comment,
answer = answer,
wrongAnswer1 = wrongAnswer1,
wrongAnswer2 = wrongAnswer2,
fillerAnswer = fillerAnswer,
fillerAllowed = fillerAllowed
}
setmetatable(o, self)
self.__index = self
return o
end
--[[Initializes the conversation engine, with callback functions for notifying
when a new topic is generated and when an answer is chosen]]
function init(_newTopicCallback, _answerCallback, _loseCallback)
newTopicCallback = _newTopicCallback
answerCallback = _answerCallback
loseCallback = _loseCallback
loadData()
end
--[[Loads conversation data from disk]]
function loadData()
for line in love.filesystem.lines(fillerPath) do
table.insert(fillerAnswers, line)
end
for line in love.filesystem.lines(topicsPath) do
local topicString = {}
local wordIterator = string.gmatch(line, '([^;]+)')
do
topicString["comment"] = wordIterator()
topicString["answer"] = wordIterator()
topicString["fillerAllowed"] = wordIterator()
end
table.insert(topicStrings, topicString)
end
end
--[[Resets the conversation engine.]]
function reset(comment)
-- Make sure questions are not in the same order
math.randomseed(os.time())
finalComment = comment
remainingTopics = deepcopy(topicStrings)
comment = ""
attentionPercent = 100
questionTimerPercent = 0
setState(CoolDownState:new(timer.Timer:new(startingTime)))
end
--[[Updates the state of the conversation engine.]]
function update(dt)
state:update(dt)
if table.getn(remainingTopics) == 0 then
remainingTopics = deepcopy(topicStrings)
end
end
-- Gets a new topic and randomly assigns answers to positions
function getNewTopic()
newTopicCallback()
topic = generateTopic()
local answers = {
topic["answer"], topic["wrongAnswer1"], topic["wrongAnswer2"]
}
comment = topic["comment"]
topPosition = popRandom(answers)
rightPosition = popRandom(answers)
bottomPosition = answers[1]
leftPosition = topic["fillerAnswer"]
state = questionState
end
function failAnswer()
love.audio.stop(wrongAnswer)
love.audio.play(wrongAnswer)
modifyAttention(-34)
end
-- Checks the selected answer against the correct answer
-- Returns true if the answer is correct or
-- if the filler answer is selected and filler answers are allowed
function checkAnswer(selectedAnswer)
answerCallback()
if selectedAnswer == "up" and topic["answer"] == topPosition then
modifyAttention(17)
return true
elseif selectedAnswer == "down" and topic["answer"] == bottomPosition then
modifyAttention(17)
return true
elseif selectedAnswer == "left" and topic["fillerAllowed"] == "true" then
return true
elseif selectedAnswer == "right" and topic["answer"] == rightPosition then
modifyAttention(17)
return true
end
return false
end
-- Draws the current topic and the rest of the conversation UI.
function draw()
drawBackground()
drawMeters()
if topic then
drawBoxes()
love.graphics.setNewFont(20)
love.graphics.printf(comment, 500, 50, 200, "center")
love.graphics.setNewFont(14)
love.graphics.printf(topPosition, 515, 205, 175, "center")
love.graphics.printf(rightPosition, 615, 305, 175, "center")
love.graphics.printf(bottomPosition, 515, 405, 175, "center")
love.graphics.printf(leftPosition, 415, 305, 175, "center")
else
love.graphics.setNewFont(20)
love.graphics.printf(finalComment, 500, 50, 200, "center")
end
end
-- Returns a new Topic instance from the remaining topics list.
function generateTopic()
local index = math.random(1, table.getn(remainingTopics))
local newTopic = remainingTopics[index]
local fillerAnswer = fillerAnswers[love.math.random(1, table.getn(
fillerAnswers))]
local wrongAnswer1 = getNewAnswer({newTopic["answer"]})
local wrongAnswer2 = getNewAnswer({newTopic["answer"], wrongAnswer1})
local topic = Topic:new(newTopic["comment"], newTopic["answer"],
wrongAnswer1, wrongAnswer2, fillerAnswer,
newTopic["fillerAllowed"])
table.remove(remainingTopics, index)
return topic
end
-- Returns a random answer from the topics table.
-- excluding answers that have already been selected.
function getNewAnswer(usedAnswers)
local answer = ""
while answer == "" do
local newAnswer = topicStrings[love.math.random(1, table.getn(
topicStrings))]["answer"]
if not tableContains(usedAnswers, newAnswer) then
answer = newAnswer
end
end
return answer
end
-- Interrupts the conversation to show a comment
-- depending on the game state that was reached
function interrupt(gameState)
print(gameState)
topic = nil
if gameState == "WrongAnswer" then
finalComment = "You're not listening! Will you please stop daydreaming?"
elseif gameState == "NearMiss" then
finalComment = "Watch out! You're always dreaming!"
elseif gameState == "EatenByScroll" then
finalComment = "Catch up! Stop daydreaming!"
elseif gameState == "Finished" then
finalComment = "We're here. Thank you for the company!"
end
comment = ""
topPosition = ""
rightPosition = ""
bottomPosition = ""
leftPosition = ""
end
-------------------------------------
-- Checks if a table contains a value.
-- @param table The table to search.
-- @param element The element to search for.
-------------------------------------
function tableContains(t, element)
for _, value in pairs(t) do if value == element then return true end end
return false
end
-------------------------------------
-- Removes and returns a random value from a table.
-- @param t The table to look in.
-------------------------------------
function popRandom(t)
random = love.math.random(1, table.getn(t))
local value = t[random]
table.remove(t, random)
return value
end
-------------------------------------
-- Deep copy implementation from http://lua-users.org/wiki/CopyTable
-- @param the table to copy.
-------------------------------------
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
-- Draws boxes around answers
function drawBoxes()
love.graphics.rectangle("line", 510, 200, 180, 60)
love.graphics.rectangle("line", 610, 300, 180, 60)
love.graphics.rectangle("line", 510, 400, 180, 60)
love.graphics.rectangle("line", 410, 300, 180, 60)
end
-- Draws the background image
function drawBackground() love.graphics.draw(backgroundImage, 400, 0) end
-- Draws the timer and attention meters
function drawMeters()
if attentionPercent > 0 then
love.graphics.setColor(26, 99, 24, 255)
love.graphics.rectangle("fill", 400, 565, attentionPercent * 4, 25)
end
if questionTimerPercent > 0 then
love.graphics.setColor(190, 52, 58, 255)
love.graphics
.rectangle("fill", 400, 530, questionTimerPercent * 400, 25)
end
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setNewFont(14)
love.graphics.printf("Timer", 400, 535, 400, "center")
love.graphics.printf("Attention", 400, 570, 400, "center")
end
-- Updates the attention value without letting it go below 0 or above 100
function modifyAttention(value)
if value > 0 then
attentionPercent = math.min(attentionPercent + value, 100)
elseif value < 0 then
attentionPercent = math.max(attentionPercent + value, 0)
end
if attentionPercent == 0 then loseCallback() end
end
function updateQuestionTimer(value) questionTimerPercent = value / topicRate end
-- ##################################################################
-- # State machine
-- ##################################################################
State = {}
function State:new(timer)
local o = {timer = timer}
setmetatable(o, self)
self.__index = self
return o
end
function State:updateTimer(dt)
local done = self.timer:update(dt)
return done
end
-- The question state counts down the question timer, which triggers a failed question state if not interrupted
QuestionState = State:new(timer)
function QuestionState:update(dt)
local selectedAnswer = input.getConversationInput()
if selectedAnswer then
if checkAnswer(selectedAnswer) then
love.audio.stop(rightAnswer)
love.audio.play(rightAnswer)
else
failAnswer()
end
setState(CoolDownState:new(timer.Timer:new(coolDownPeriod)))
else
if (self.timer:update(dt)) then
failAnswer()
setState(CoolDownState:new(timer.Timer:new(coolDownPeriod)))
end
updateQuestionTimer(self.timer.currentTime)
end
end
-- The cooldown state counts down the cooldown timer, which triggers a new question and transfers control to the question state
CoolDownState = State:new(timer)
function CoolDownState:update(dt)
if (self:updateTimer(dt)) then
getNewTopic()
input.resetConversation()
setState(QuestionState:new(timer.Timer:new(topicRate)))
end
end
function setState(newState) state = newState end