forked from niavlys/memoryKivy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
429 lines (359 loc) · 15.3 KB
/
main.py
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""
Copyright (c) 2012, Sylvain Alborini
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import kivy
kivy.require('1.0.9')
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.slider import Slider
from kivy.uix.scatter import Scatter
from kivy.uix.togglebutton import ToggleButton
from kivy.core.audio import SoundLoader
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.animation import Animation
from kivy.properties import StringProperty, ObjectProperty,NumericProperty
from kivy.uix.progressbar import ProgressBar
from random import choice,shuffle
from glob import glob
from os.path import dirname, join, basename,sep
import json
from kivy.core.window import Window
DEFAULT_SHOWTIME = 10
DEFAULT_NBITEMS = 12
MAX_NBITEMS = None
def bestRatio(nb,width,height):
row=1
correctRatio=1.
minErr=None
nbparrow = nb/row
if nb%row !=0:
nbparrow+=1
x = float(width)/nbparrow
y = float(height)/row
ratio=x/y
minErr=abs(ratio-correctRatio)
while ratio<correctRatio:
row+=1
nbparrow = nb/row
if nb%row !=0:
nbparrow+=1
x = float(width)/nbparrow
y = float(height)/row
ratio=x/y
if abs(ratio-correctRatio)>minErr:
row-=1
minErr = abs(ratio-correctRatio)
return row
class MemoryButton(Button):
done=False
playsound=True
filenameSound = StringProperty(None)
filenameIcon = StringProperty(None)
sound = ObjectProperty(None)
background = ObjectProperty(None)
background_hide = ObjectProperty(None)
#background_down = ObjectProperty(None)
background_normal = ObjectProperty(None)
def on_filenameSound(self, instance, value):
# the first time that the filename is set, we are loading the sample
if self.sound is None:
self.sound = SoundLoader.load(value)
def on_filenameIcon(self, instance, value):
# the first time that the filename is set, we are loading the sample
if self.background_normal is None:
self.background_normal=value
self.background = value
self.background_hide = self.background_down
@classmethod
def toggleSound(cls,instance):
instance.text = ["Sound On" if instance.state == 'normal' else "Sound Off"][0]
cls.playsound = instance.state == 'normal'
def on_press(self):
if self.parent.state=='OK' and not self.done:
if self.parent.first is None:
self.parent.first = self
self.background_down,self.background_normal = self.background_normal,self.background_down
else:
if self is self.parent.first:
self.parent.first==None
elif self.parent.first.filenameIcon == self.filenameIcon:
print("youhou!!")
self.parent.left+=1
if self.playsound:
if self.sound.status != 'stop':
self.sound.stop()
self.sound.play()
self.background_down,self.background_normal = self.background,self.background
self.parent.first.background_down,self.parent.first.background_normal = self.parent.first.background,self.parent.first.background
self.done=True
self.parent.first.done=True
self.parent.first = None
#check termination
if self.parent.left == self.parent.items:
self.parent.gameOver()
Clock.unschedule(self.parent.elapsedTime)
else:
self.parent.missed += 1
self.parent.first.background_down,self.parent.first.background_normal = self.parent.first.background_normal,self.parent.first.background_down
self.parent.first =None
class MemoryLayout(GridLayout):
left = NumericProperty(0) #left items to find
items = NumericProperty(0) #total number of items
level = NumericProperty(0) #seconds to count down
countdown = NumericProperty(0)
missed = NumericProperty(0) # number of missed items
elapsed = NumericProperty(0)
def __init__(self, **kwargs):
super(MemoryLayout, self).__init__(**kwargs)
self.state = ""
self.first=None
self.level=kwargs["level"]
self.items=kwargs["items"]
self.countdown= self.level
def toggleButtons(self,state):
for i in self.children:
i.background_down,i.background_normal = i.background_normal,i.background_down
self.state=state
def hideButtons(self):
for i in self.children:
i.done=False
i.background_down,i.background_normal = i.background_hide,i.background_hide
def showButtons(self):
for i in self.children:
i.background_normal = i.background
def elapsedTime(self,dt):
self.elapsed += dt
def startGame(self,dt):
self.reset()
Clock.schedule_interval(self.initialCountdown,1)
def initialCountdown(self,dt):
if self.countdown == -1:
Clock.unschedule(self.initialCountdown)
self.toggleButtons("OK")
Clock.schedule_interval(self.elapsedTime,0.1)
else:
if not hasattr(self.parent.parent,'countdown'):
self.parent.parent.countdown=Label(text="")
self.parent.parent.add_widget(self.parent.parent.countdown)
popup=self.parent.parent.countdown
popup.text=''
popup.font_size=12
popup.color=(0,0,0,1)
popup.text=str(self.countdown)
Animation(color=(1,1,1,0),font_size=150).start(popup)
self.countdown -= 1
def resetTime(self,instance,newLevel):
self.level=int(newLevel)
def resetNbItem(self,instance,newNb):
self.items = int(newNb)
def reset(self):
self.countdown = self.level
self.first = None
self.left = 0
self.elapsed = 0
self.missed = 0
self.hideButtons()
self.state = ''
self.updateNbItems()
def restartGame(self,inst):
self.reset()
self.showButtons()
Clock.schedule_interval(self.initialCountdown,1)
def updateNbItems(self):
if self.items != len(self.children):
#update self.rows to keep acceptable ratio
newRow = bestRatio(self.items*2,self.width,self.height)
self.clear_widgets()
self.rows=newRow
shuffle(icons)
iicons=icons[:self.items]
iicons=iicons+iicons
shuffle(iicons)
for i in iicons:
s = i.split(".png")[0].split(sep)[1]
if s in sounds:
aSound = choice(sounds[s])
else:
aSound = sounds['default'][0]
btn = MemoryButton(
text="",
filenameIcon=i,
filenameSound=aSound,
)
self.add_widget(btn)
else:
shuffle(self.children)
def saveLevel(self):
fileName = join(App.get_running_app().user_data_dir,'level.dat')
with open(fileName,'w') as fd:
userData={"items":self.items,"level":self.level}
json.dump(userData,fd)
def gameOver(self):
# calculate score
score = 100./self.level + 100.*self.items - 10.*self.missed + 100./self.elapsed
print("done!",score)
self.saveLevel()
content2 = BoxLayout(orientation='vertical',spacing=10)
#content.add_widget(Label(text='score: %d'%int(score)))
content = BoxLayout(orientation='vertical',size_hint_y=.7)
#change show time
labelSlider = LabelTimeSlider(text='Initial Show time: %s s'%self.level)
content.add_widget(labelSlider)
newLevel = Slider(min=1, max=30, value=self.level)
content.add_widget(newLevel)
newLevel.bind(value = labelSlider.update)
newLevel.bind(value = self.resetTime)
#change number of items
labelNb = LabelNb(text='Number of items: %s'%self.items)
content.add_widget(labelNb)
nb_items = Slider(min=5, max = MAX_NBITEMS, value = self.items )
content.add_widget(nb_items)
nb_items.bind(value = labelNb.update)
nb_items.bind(value = self.resetNbItem)
content2.add_widget(content)
replay = Button(text='Replay!')
credits = Button(text='Credits')
action = BoxLayout(orientation='horizontal',size_hint_y=.3)
action.add_widget(replay)
action.add_widget(credits)
content2.add_widget(action)
popup = PopupGameOver(title='Congratulations! your score: %d'%int(score),
content=content2,
size_hint=(0.5, 0.5),pos_hint={'x':0.25, 'y':0.25},
auto_dismiss=False)
replay.bind(on_press=popup.replay)
replay.bind(on_press=self.restartGame)
credits.bind(on_press=popup.credits)
popup.open()
class ScrollableLabel(ScrollView):
'''
use it thisly -> scrollablelabel = ScrollableLabel().build("put your big bunch of text right here")
or
ScrollableLabel().build() <- thusly with no argument to just get a very big bunch of text as a demo
scrolls x and y default
'''
def build(self,textinput,size):
self.summary_label = Label(text="",text_size=(size,None),
size_hint_y=None,size_hint_x=None)
self.summary_label.bind(texture_size=self._set_summary_height)
# remove the above bind
self.summary_label.text = str(textinput)
#and try setting height in the following line
self.sv = ScrollView(do_scroll_x=False)
# it does not scroll the scroll view.
self.sv.add_widget(self.summary_label)
return self.sv
def _set_summary_height(self, instance, size):
instance.height = size[1]
instance.width = size[0]
class PopupGameOver(Popup):
def replay(self,inst):
self.dismiss()
def credits(self,inst):
with open(join(dirname(__file__),'credits'),'r') as f:
ti=f.read()
content = BoxLayout(orientation='vertical')
close = Button(text='Close',size_hint=(1,.1))
sv = ScrollableLabel().build(ti,Window.width-20)
content.add_widget(sv)
content.add_widget(close)
popup = Popup(title='Credits:',
content=content, auto_dismiss=False
)
close.bind(on_press=popup.dismiss)
popup.open()
class LabelTimeSlider(Label):
def update(self,instance,value):
self.text="Initial Show time: %d s"%int(value)
class LabelNb(Label):
def update(self,instance,value):
self.text="Number of items: %d"%int(value)
class MyPb(ProgressBar):
def foundAnItem(self,instance,value):
self.value = value
def newNbItems(self,instance,value):
self.value = value
self.max = value
class LabelScore(Label):
def updateTime(self,instance,value):
self.text="Time: %0.2f s"%value
class LabelMissed(Label):
def update(self,instance,value):
self.text="Missed: %d"%value
def loadData():
sounds={}
icons=[]
for s in glob(join(dirname(__file__),"sounds", '*.wav')):
name=basename(s[:-4]).split("_")[0]
if name in sounds:
sounds[name].append(s)
else:
sounds[name]=[s]
for i in glob(join(dirname(__file__),"icons", '*.png')):
icons.append(i)
return sounds,icons
def showmissingSounds():
missing=[]
for i in icons:
s = i.split(".png")[0].split(sep)[1]
if not s in sounds:
missing.append(s)
print("missing sounds for %d animals: %s"%(len(missing),missing))
class MyAnimalsApp(App):
def loadLevel(self):
fileName = join(App.get_running_app().user_data_dir,'level.dat')
try:
with open(fileName) as fd:
userData={}
userData = json.load(fd)
return userData["items"],userData["level"]
except:
return DEFAULT_NBITEMS , DEFAULT_SHOWTIME
def build(self):
self.icon = 'memoIcon.png'
self.title = 'Kivy Memory'
global sounds,icons
sounds,icons=loadData()
#showmissingSounds()
global MAX_NBITEMS
MAX_NBITEMS = len(icons)
items,level = self.loadLevel()
g = MemoryLayout(rows=4,items = items, level=level,size_hint=(1,.9))
config = BoxLayout(orientation='horizontal',spacing=10, size_hint=(1,.1))
sound = ToggleButton(text='Sound On', size_hint=(0.15,1))
sound.bind(on_press=MemoryButton.toggleSound)
pb = MyPb(max=items, size_hint=(0.55,1))
score = LabelScore(text="Time: 0 s",size_hint=(0.15,1))
missed = LabelMissed(text="Missed: 0",size_hint=(0.15,1))
config.add_widget(pb)
config.add_widget(score)
config.add_widget(missed)
config.add_widget(sound)
g.bind(missed=missed.update)
g.bind(elapsed=score.updateTime)
g.bind(left=pb.foundAnItem)
g.bind(items=pb.newNbItems)
playZone = BoxLayout(orientation='vertical')
playZone.add_widget(g)
playZone.add_widget(config)
root=FloatLayout()
root.add_widget(Image(source='Jungle_Background_-_by-vectorjungle.jpg',allow_stretch=True,keep_ratio=False))
root.add_widget(playZone)
#Clock.schedule_interval(g.initialCountdown,1)
Clock.schedule_once(g.startGame,3)
return root
if __name__ in ('__main__', '__android__'):
MyAnimalsApp().run()