This repository has been archived by the owner on Nov 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 205
/
main.py
492 lines (415 loc) · 15.1 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
__version__ = '1.3.2'
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, OptionProperty, ObjectProperty
from kivy.graphics import Color, BorderImage
from kivy.clock import Clock
from kivy.vector import Vector
from kivy.metrics import dp
from kivy.animation import Animation
from kivy.utils import get_color_from_hex
from kivy.core.window import Window
from kivy.utils import platform
from kivy.factory import Factory
from random import choice, random
platform = platform()
app = None
if platform == 'android':
# Support for Google Play
import gs_android
leaderboard_highscore = 'CgkI0InGg4IYEAIQBg'
achievement_block_32 = 'CgkI0InGg4IYEAIQCg'
achievement_block_64 = 'CgkI0InGg4IYEAIQCQ'
achievement_block_128 = 'CgkI0InGg4IYEAIQAQ'
achievement_block_256 = 'CgkI0InGg4IYEAIQAg'
achievement_block_512 = 'CgkI0InGg4IYEAIQAw'
achievement_block_1024 = 'CgkI0InGg4IYEAIQBA'
achievement_block_2048 = 'CgkI0InGg4IYEAIQBQ'
achievement_block_4096 = 'CgkI0InGg4IYEAIQEg'
achievement_100x_block_512 = 'CgkI0InGg4IYEAIQDA'
achievement_1000x_block_512 = 'CgkI0InGg4IYEAIQDQ'
achievement_100x_block_1024 = 'CgkI0InGg4IYEAIQDg'
achievement_1000x_block_1024 = 'CgkI0InGg4IYEAIQDw'
achievement_10x_block_2048 = 'CgkI0InGg4IYEAIQEA'
achievements = {
32: achievement_block_32,
64: achievement_block_64,
128: achievement_block_128,
256: achievement_block_256,
512: achievement_block_512,
1024: achievement_block_1024,
2048: achievement_block_2048,
4096: achievement_block_4096}
from kivy.uix.popup import Popup
class GooglePlayPopup(Popup):
pass
else:
achievements = {}
class ButtonBehavior(object):
# XXX this is a port of the Kivy 1.8.0 version, the current android versino
# still use 1.7.2. This is going to be removed soon.
state = OptionProperty('normal', options=('normal', 'down'))
last_touch = ObjectProperty(None)
def __init__(self, **kwargs):
self.register_event_type('on_press')
self.register_event_type('on_release')
super(ButtonBehavior, self).__init__(**kwargs)
def _do_press(self):
self.state = 'down'
def _do_release(self):
self.state = 'normal'
def on_touch_down(self, touch):
if super(ButtonBehavior, self).on_touch_down(touch):
return True
if touch.is_mouse_scrolling:
return False
if not self.collide_point(touch.x, touch.y):
return False
if self in touch.ud:
return False
touch.grab(self)
touch.ud[self] = True
self.last_touch = touch
self._do_press()
self.dispatch('on_press')
return True
def on_touch_move(self, touch):
if touch.grab_current is self:
return True
if super(ButtonBehavior, self).on_touch_move(touch):
return True
return self in touch.ud
def on_touch_up(self, touch):
if touch.grab_current is not self:
return super(ButtonBehavior, self).on_touch_up(touch)
assert(self in touch.ud)
touch.ungrab(self)
self.last_touch = touch
self._do_release()
self.dispatch('on_release')
return True
def on_press(self):
pass
def on_release(self):
pass
class Number(Widget):
number = NumericProperty(2)
scale = NumericProperty(.1)
colors = {
2: get_color_from_hex('#eee4da'),
4: get_color_from_hex('#ede0c8'),
8: get_color_from_hex('#f2b179'),
16: get_color_from_hex('#f59563'),
32: get_color_from_hex('#f67c5f'),
64: get_color_from_hex('#f65e3b'),
128: get_color_from_hex('#edcf72'),
256: get_color_from_hex('#edcc61'),
512: get_color_from_hex('#edc850'),
1024: get_color_from_hex('#edc53f'),
2048: get_color_from_hex('#edc22e'),
4096: get_color_from_hex('#ed702e'),
8192: get_color_from_hex('#ed4c2e')}
def __init__(self, **kwargs):
super(Number, self).__init__(**kwargs)
anim = Animation(scale=1., d=.15, t='out_quad')
anim.bind(on_complete=self.clean_canvas)
anim.start(self)
def clean_canvas(self, *args):
self.canvas.before.clear()
self.canvas.after.clear()
def move_to_and_destroy(self, pos):
self.destroy()
#anim = Animation(opacity=0., d=.25, t='out_quad')
#anim.bind(on_complete=self.destroy)
#anim.start(self)
def destroy(self, *args):
self.parent.remove_widget(self)
def move_to(self, pos):
if self.pos == pos:
return
Animation(pos=pos, d=.1, t='out_quad').start(self)
def on_number(self, instance, value):
if platform == 'android':
if value in achievements:
app.gs_unlock(achievements[value])
if value == 512:
app.gs_increment(achievement_100x_block_512)
app.gs_increment(achievement_1000x_block_512)
elif value == 1024:
app.gs_increment(achievement_100x_block_1024)
app.gs_increment(achievement_1000x_block_1024)
elif value == 2048:
app.gs_increment(achievement_10x_block_2048)
class Game2048(Widget):
cube_size = NumericProperty(10)
cube_padding = NumericProperty(10)
score = NumericProperty(0)
def __init__(self, **kwargs):
super(Game2048, self).__init__()
self.grid = [
[None, None, None, None],
[None, None, None, None],
[None, None, None, None],
[None, None, None, None]]
# bind keyboard
Window.bind(on_key_down=self.on_key_down)
Window.on_keyboard = lambda *x: None
self.restart()
def on_key_down(self, window, key, *args):
moved = False
if key == 273:
moved = self.move_topdown(True, from_keyboard=True)
elif key == 274:
moved = self.move_topdown(False, from_keyboard=True)
elif key == 276:
moved = self.move_leftright(False, from_keyboard=True)
elif key == 275:
moved = self.move_leftright(True, from_keyboard=True)
elif key == 27 and platform == 'android':
from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
PythonActivity.mActivity.moveTaskToBack(True)
return True
if not self.check_end() and moved:
Clock.schedule_once(self.spawn_number, .20)
def rebuild_background(self):
self.canvas.before.clear()
with self.canvas.before:
Color(0xbb / 255., 0xad / 255., 0xa0 / 255.)
BorderImage(pos=self.pos, size=self.size, source='data/round.png')
Color(0xcc / 255., 0xc0 / 255., 0xb3 / 255.)
csize = self.cube_size, self.cube_size
for ix, iy in self.iterate_pos():
BorderImage(pos=self.index_to_pos(ix, iy), size=csize,
source='data/round.png')
def reposition(self, *args):
self.rebuild_background()
# calculate the size of a number
l = min(self.width, self.height)
padding = (l / 4.) / 8.
cube_size = (l - (padding * 5)) / 4.
self.cube_size = cube_size
self.cube_padding = padding
for ix, iy, number in self.iterate():
number.size = cube_size, cube_size
number.pos = self.index_to_pos(ix, iy)
def iterate(self):
for ix, iy in self.iterate_pos():
child = self.grid[ix][iy]
if child:
yield ix, iy, child
def iterate_empty(self):
for ix, iy in self.iterate_pos():
child = self.grid[ix][iy]
if not child:
yield ix, iy
def iterate_pos(self):
for ix in range(4):
for iy in range(4):
yield ix, iy
def index_to_pos(self, ix, iy):
padding = self.cube_padding
cube_size = self.cube_size
return [
(self.x + padding) + ix * (cube_size + padding),
(self.y + padding) + iy * (cube_size + padding)]
def spawn_number(self, *args):
empty = list(self.iterate_empty())
if not empty:
return
value = 2 if random() < .9 else 4
ix, iy = choice(empty)
self.spawn_number_at(ix, iy, value)
def spawn_number_at(self, ix, iy, value):
number = Number(
size=(self.cube_size, self.cube_size),
pos=self.index_to_pos(ix, iy),
number=value)
self.grid[ix][iy] = number
self.add_widget(number)
def on_touch_up(self, touch):
v = Vector(touch.pos) - Vector(touch.opos)
if v.length() < dp(20):
return
# detect direction
dx, dy = v
if abs(dx) > abs(dy):
self.move_leftright(dx > 0)
else:
self.move_topdown(dy > 0)
return True
def move_leftright(self, right, from_keyboard=False):
r = range(3, -1, -1) if right else range(4)
grid = self.grid
moved = False
for iy in range(4):
# get all the cube for the current line
cubes = []
for ix in r:
cube = grid[ix][iy]
if cube:
cubes.append(cube)
# combine them
self.combine(cubes)
# update the grid
for ix in r:
cube = cubes.pop(0) if cubes else None
if grid[ix][iy] != cube:
moved = True
grid[ix][iy] = cube
if not cube:
continue
pos = self.index_to_pos(ix, iy)
if cube.pos != pos:
cube.move_to(pos)
if from_keyboard:
return moved
elif not self.check_end() and moved:
Clock.schedule_once(self.spawn_number, .20)
def move_topdown(self, top, from_keyboard=False):
r = range(3, -1, -1) if top else range(4)
grid = self.grid
moved = False
for ix in range(4):
# get all the cube for the current line
cubes = []
for iy in r:
cube = grid[ix][iy]
if cube:
cubes.append(cube)
# combine them
self.combine(cubes)
# update the grid
for iy in r:
cube = cubes.pop(0) if cubes else None
if grid[ix][iy] != cube:
moved = True
grid[ix][iy] = cube
if not cube:
continue
pos = self.index_to_pos(ix, iy)
if cube.pos != pos:
cube.move_to(pos)
if from_keyboard:
return moved
elif not self.check_end() and moved:
Clock.schedule_once(self.spawn_number, .20)
def combine(self, cubes):
if len(cubes) <= 1:
return cubes
index = 0
while index < len(cubes) - 1:
cube1 = cubes[index]
cube2 = cubes[index + 1]
if cube1.number == cube2.number:
cube1.number *= 2
self.score += cube1.number
cube2.move_to_and_destroy(cube1.pos)
del cubes[index + 1]
index += 1
def check_end(self):
# we still have empty space
if any(self.iterate_empty()):
return False
# check if 2 numbers of the same type are near each others
if self.have_available_moves():
return False
self.end()
return True
def have_available_moves(self):
grid = self.grid
for iy in range(4):
for ix in range(3):
cube1 = grid[ix][iy]
cube2 = grid[ix + 1][iy]
if cube1.number == cube2.number:
return True
for ix in range(4):
for iy in range(3):
cube1 = grid[ix][iy]
cube2 = grid[ix][iy + 1]
if cube1.number == cube2.number:
return True
def end(self):
end = self.ids.end.__self__
self.remove_widget(end)
self.add_widget(end)
text = 'Game\nover!'
for ix, iy, cube in self.iterate():
if cube.number == 2048:
text = 'WIN !'
self.ids.end_label.text = text
Animation(opacity=1., d=.5).start(end)
app.gs_score(self.score)
def restart(self):
self.score = 0
for ix, iy, child in self.iterate():
child.destroy()
self.grid = [
[None, None, None, None],
[None, None, None, None],
[None, None, None, None],
[None, None, None, None]]
self.reposition()
Clock.schedule_once(self.spawn_number, .1)
Clock.schedule_once(self.spawn_number, .1)
self.ids.end.opacity = 0
class Game2048App(App):
use_kivy_settings = False
def build_config(self, config):
if platform == 'android':
config.setdefaults('play', {'use_google_play': '0'})
def build(self):
global app
app = self
if platform == 'android':
self.use_google_play = self.config.getint('play', 'use_google_play')
if self.use_google_play:
gs_android.setup(self)
else:
Clock.schedule_once(self.ask_google_play, .5)
else:
# remove all the leaderboard and achievement buttons
scoring = self.root.ids.scoring
scoring.parent.remove_widget(scoring)
def gs_increment(self, uid):
if platform == 'android' and self.use_google_play:
gs_android.increment(uid, 1)
def gs_unlock(self, uid):
if platform == 'android' and self.use_google_play:
gs_android.unlock(uid)
def gs_score(self, score):
if platform == 'android' and self.use_google_play:
gs_android.leaderboard(leaderboard_highscore, score)
def gs_show_achievements(self):
if platform == 'android':
if self.use_google_play:
gs_android.show_achievements()
else:
self.ask_google_play()
def gs_show_leaderboard(self):
if platform == 'android':
if self.use_google_play:
gs_android.show_leaderboard(leaderboard_highscore)
else:
self.ask_google_play()
def ask_google_play(self, *args):
popup = GooglePlayPopup()
popup.open()
def activate_google_play(self):
self.config.set('play', 'use_google_play', '1')
self.config.write()
self.use_google_play = 1
gs_android.setup(self)
def on_pause(self):
if platform == 'android':
gs_android.on_stop()
return True
def on_resume(self):
if platform == 'android':
gs_android.on_start()
def _on_keyboard_settings(self, *args):
return
if __name__ == '__main__':
Factory.register('ButtonBehavior', cls=ButtonBehavior)
Game2048App().run()