Source

Memoreek / src / memory.py

The branch 'new_game' does not exist.
  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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#-*- coding: utf-8 -*-

##############################################################################
#
# This file is part of Geezle
#
# Copyright (C) 2012  César Bustíos Benites
#
# Geezle is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Geezle is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# Author: César Bustíos Benites <cesarbustios@gmail.com>
# Email: cesarbustios@gmail.com
# Google+: https://plus.google.com/u/0/103603507868093099204
# License: GPL v3
#
# Geezle was based on Al Sweigart's game from the book "Making Games with
# Python and Pygame"
#
##############################################################################

import sys
import random
import os
from os.path import abspath, dirname, join

import pygame
from pygame.locals import *


# Paths
PROJECT_PATH = abspath(dirname(__file__))
IMAGES_PATH = join(PROJECT_PATH, '../data/images')
FONTS_PATH = join(PROJECT_PATH, '../data/fonts')
SOUNDS_PATH = join(PROJECT_PATH, '../data/sounds')
BACKGROUND_IMG_PATH = join(IMAGES_PATH, 'memory_background.jpg')
BACKGROUND_MUSIC_PATH = join(SOUNDS_PATH, 'memory_music.mp3')

# Main screen resolution
SCREEN_RESOLUTION = (800, 600)

# Game and board settings
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
BOX_SIZE = 40
BOX_GAP = 10
BOARD_COLS = 9
BOARD_ROWS = 6
BOARD_WIDTH = (BOARD_COLS * BOX_SIZE) + ((BOARD_COLS - 1) * BOX_GAP)
BOARD_HEIGHT = (BOARD_ROWS * BOX_SIZE) + ((BOARD_ROWS - 1) * BOX_GAP)
IMAGES_NEEDED = (BOARD_COLS * BOARD_ROWS) / 2
HIGHLIGHT_WIDTH = 3
X_MARGIN = 40
Y_MARGIN = 40
FONT_STYLE = 'frontier.ttf'

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (25, 25, 255)
GOLD = (205, 180, 12)
HIGHLIGHT_COLOR = BLUE

pygame.init()
SCREEN = pygame.display.set_mode(SCREEN_RESOLUTION)
CLOCK = pygame.time.Clock()

# Images
BOX_IMG = pygame.image.load(join(IMAGES_PATH, 'box1.png')).convert()
BACKGROUND_IMG = pygame.image.load(BACKGROUND_IMG_PATH).convert()

# Loading and playing background music:
pygame.mixer.music.load(BACKGROUND_MUSIC_PATH)
pygame.mixer.music.play(-1, 0.0)


def main():
    """
    Main shit
    """
    pygame.display.set_caption('Geezle - Memory Puzzle')

    # Initial data
    logos_path = join(IMAGES_PATH, 'logos/distros')
    board = generate_board(logos_path, False)
    new_game = True
    running = True
    box_img = BOX_IMG

    # Number of moves
    score = 0

    # Pixel coordinates for mouse events
    x = 0
    y = 0

    # First selected logo [row, col]
    first_choice = None

    # Block mouse motion events
    pygame.event.set_blocked(pygame.MOUSEMOTION)

    while running:
        # Background image
        SCREEN.blit(BACKGROUND_IMG, (0, 0))
        draw_table(WHITE, BLACK)
        draw_board(board, box_img)

        # Display options: New game, Quit, Sound, etc.
        options = display_game_options_and_score(str(score))

        # New board?
        if new_game:
            new_game_options = display_new_game_settings()

        # Check if game is over
        if all_matched(board['revealed']):
            display_game_over_message()

        clicked = False
        pygame.display.update()

        # Events handling
        event = pygame.event.wait()
        if event.type == QUIT:
            running = False
        elif event.type == MOUSEBUTTONUP:
            if event.button == 1:
                x, y = event.pos
                clicked = True

        # Get box at pixel (x,y)
        row, col = get_box(board, x, y)
        if row != None and col != None and new_game is not True:
            # Box is clicked
            if not board['revealed'][row][col] and clicked:
                reveal_box(board, row, col, box_img)
                if first_choice == None:
                    first_choice = (row, col)
                else:
                    logo1 = board['logos'][first_choice[0]][first_choice[1]]
                    logo2 = board['logos'][row][col]

                    # If your memory sucks, mark both as unrevealed
                    if logo1 != logo2:
                        pygame.time.delay(500)
                        board['revealed'][first_choice[0]][first_choice[1]] = False
                        board['revealed'][row][col] = False
                    else:
                        # TODO: Animate matched logos or something?
                        pass

                    score += 1
                    first_choice = None

        if clicked and new_game is not True:
            # New game?
            if options['new_game'].collidepoint(x, y):
                new_game = True
                score = 0
            # Quit!!!???
            elif options['quit'].collidepoint(x, y):
                running = False
            elif options['blue_box'].collidepoint(x, y):
                path = join(IMAGES_PATH, 'box1.png')
                box_img = pygame.image.load(path).convert()
            elif options['green_box'].collidepoint(x, y):
                path = join(IMAGES_PATH, 'box2.png')
                box_img = pygame.image.load(path).convert()
            elif options['purple_box'].collidepoint(x, y):
                path = join(IMAGES_PATH, 'box3.png')
                box_img = pygame.image.load(path).convert()
            elif options['tux_box'].collidepoint(x, y):
                path = join(IMAGES_PATH, 'box4.png')
                box_img = pygame.image.load(path).convert_alpha()

        if clicked and new_game is True:
            if new_game_options['distros']['rect'].collidepoint(x,y):
                logos_path = new_game_options['distros']['path']
                board = generate_board(logos_path, False)
                new_game = False
            elif new_game_options['open_source']['rect'].collidepoint(x,y):
                logos_path = new_game_options['open_source']['path']
                board = generate_board(logos_path, False)
                new_game = False
            elif new_game_options['programming']['rect'].collidepoint(x,y):
                logos_path = new_game_options['programming']['path']
                board = generate_board(logos_path, False)
                new_game = False

    pygame.quit()


def animate_unrevealed(rect, box_img):
    """
    Scales the unrevealed image when clicked
    """
    height = box_img.get_height()
    width = box_img.get_width()
    x = rect.x
    y = rect.y

    while height >= 0 or width >= 0:
        # Temporary surface for replacing previous unrevealed box image
        tmp = pygame.surface.Surface((BOX_SIZE, BOX_SIZE))
        tmp.fill(WHITE)
        SCREEN.blit(tmp, (rect.x, rect.y))

        # Scale and blit the image
        box_img = pygame.transform.scale(box_img, (width, height))
        SCREEN.blit(box_img, (x, y))
        pygame.time.delay(25)
        pygame.display.update()
        height -= 5
        width -= 5

        # TODO: Calculate
        x += 3.5
        y += 3.5


def highlight_box(board, row, col):
    """
    Highlights a box when mouse is over
    """
    rect = board['rects'][row][col]
    r = pygame.rect.Rect(rect.left-5, rect.top-5, BOX_SIZE+10, BOX_SIZE+10)
    pygame.draw.rect(SCREEN, HIGHLIGHT_COLOR, r, HIGHLIGHT_WIDTH)


def get_box(board, x, y):
    """
    Return [row, col] position of box at pixel position (x, y) if found.
    """
    for row in range(BOARD_ROWS):
        for col in range(BOARD_COLS):
            rect = board['rects'][row][col]
            if rect.collidepoint(x, y):
                return row, col
    return None, None


def display_game_over_message():
    """
    Message for logo masters.
    """
    # Font
    win_font = pygame.font.Font(join(FONTS_PATH, FONT_STYLE), 96)

    # Surface
    win_surface = win_font.render('You win!', True, GOLD)

    # Rect
    win_rect = win_surface.get_rect()

    # Position
    left = (BOARD_WIDTH / 2) + X_MARGIN
    top = (BOARD_HEIGHT / 2) + Y_MARGIN
    win_rect.center = (left, top)

    SCREEN.blit(win_surface, win_rect)


def display_game_options_and_score(score):
    """
    Display options and score. Returns rects for colliding process
    """
    # Display current score (moves)
    display_score(score)

    x = SCREEN_RESOLUTION[0] - 150
    y = 95

    # Buttons
    new_game_surface = pygame.image.load(join(IMAGES_PATH, 'buttons/new_game.png')).convert()
    quit_surface = pygame.image.load(join(IMAGES_PATH, 'buttons/quit.png')).convert()

    # Rects
    new_game_rect = new_game_surface.get_rect()
    quit_rect = quit_surface.get_rect()
    new_game_rect.center = (x, y)
    quit_rect.center = (x, y + 60)

    # Show the options
    SCREEN.blit(new_game_surface, new_game_rect)
    SCREEN.blit(quit_surface, quit_rect)

    option_rects = {
        'new_game': new_game_rect,
        'quit': quit_rect,
    }

    # Change the ugly box image? Tux maybe?
    box_rects = display_box_options()

    option_rects.update(box_rects)

    return option_rects


def display_score(score):
    """
    Display the current score (moves)
    """
    score_font = pygame.font.Font(join(FONTS_PATH, FONT_STYLE), 20)
    score_text = 'Moves: %s' % str(score.zfill(3))
    score_surface = score_font.render(score_text, True, GOLD)

    # Rect
    score_rect = score_surface.get_rect()
    score_rect.center = (SCREEN_RESOLUTION[0] - 150, 35)

    # Show it
    SCREEN.blit(score_surface, score_rect)


def display_box_options():
    """
    For box image customization.
    """
    x = SCREEN_RESOLUTION[0] - 150
    y = 280

    # Text
    option_font = pygame.font.Font(join(FONTS_PATH, FONT_STYLE), 20)
    option_surface = option_font.render('Box style', True, GOLD)
    option_rect = option_surface.get_rect()
    option_rect.center = (x, y)

    SCREEN.blit(option_surface, option_rect)

    # Surfaces
    box1_surface = pygame.image.load(join(IMAGES_PATH, 'box1_thumb.png')).convert()
    box2_surface = pygame.image.load(join(IMAGES_PATH, 'box2_thumb.png')).convert()
    box3_surface = pygame.image.load(join(IMAGES_PATH, 'box3_thumb.png')).convert()
    box4_surface = pygame.image.load(join(IMAGES_PATH, 'box4_thumb.png')).convert_alpha()

    # Rects
    box1_rect = box1_surface.get_rect()
    box2_rect = box1_surface.get_rect()
    box3_rect = box1_surface.get_rect()
    box4_rect = box1_surface.get_rect()

    # Positions
    box1_rect.center = (x - 60, y + 40)
    box2_rect.center = (x -20, y + 40)
    box3_rect.center = (x + 20, y + 40)
    box4_rect.center = (x + 60, y + 40)

    # Show them
    SCREEN.blit(box1_surface, box1_rect)
    SCREEN.blit(box2_surface, box2_rect)
    SCREEN.blit(box3_surface, box3_rect)
    SCREEN.blit(box4_surface, box4_rect)

    box_rects = {
        'blue_box': box1_rect,
        'green_box': box2_rect,
        'purple_box': box3_rect,
        'tux_box': box4_rect,
    }

    return box_rects


def display_new_game_settings():
    """
    For choosing icon theme. Returns a dict of rects for colliding process
    """
    # Temporal surface for transparency
    tmp_surface = pygame.Surface(SCREEN_RESOLUTION)
    tmp_surface.set_alpha(100)
    tmp_surface.fill((0,0,0))
    SCREEN.blit(tmp_surface, (0,0))

    # Background image for holding new game options
    img_path = join(IMAGES_PATH, 'new_game_bg.png')
    new_game_img = pygame.image.load(img_path).convert()

    # Top left corner of background image
    left = 0
    top = (SCREEN_RESOLUTION[1] / 2) - (new_game_img.get_height() / 2)

    # Get the image rect and set position on the screen
    new_game_rect = new_game_img.get_rect()
    new_game_rect.left = left
    new_game_rect.top = top

    SCREEN.blit(new_game_img, new_game_rect)

    # Title font and position
    font = pygame.font.Font(join(FONTS_PATH, 'nitemare.ttf'), 40)
    title_font = font.render('Choose Icon Set', True, WHITE)
    title_rect = title_font.get_rect()
    center = (left + (SCREEN_RESOLUTION[0] / 2), top + 30)
    title_rect.center = center

    SCREEN.blit(title_font, title_rect)

    # Icons for choosing theme
    path = join(IMAGES_PATH, 'distros.png')
    distros_img = pygame.image.load(path).convert()

    path = join(IMAGES_PATH, 'open_source.png')
    open_source_img = pygame.image.load(path).convert()

    path = join(IMAGES_PATH, 'programming.png')
    programming_img = pygame.image.load(path).convert()

    # Icons rects for colliding
    distros_rect = distros_img.get_rect()
    open_source_rect = open_source_img.get_rect()
    programming_rect = programming_img.get_rect()

    # Set the positions for the icons
    left = SCREEN_RESOLUTION[0] / 2
    top = top + 100

    distros_rect.center = (left - 200, top)
    open_source_rect.center = (left, top)
    programming_rect.center = (left + 200, top)

    SCREEN.blit(distros_img, distros_rect)
    SCREEN.blit(open_source_img, open_source_rect)
    SCREEN.blit(programming_img, programming_rect)

    # Return each option with its rect and path to images
    distros_path = join(IMAGES_PATH, 'logos/distros')
    open_source_path = join(IMAGES_PATH, 'logos/tools')
    programming_path = join(IMAGES_PATH, 'logos/languages')

    options = {
        'distros': {'rect': distros_rect, 'path': distros_path},
        'open_source': {'rect': open_source_rect, 'path': open_source_path},
        'programming': {'rect': programming_rect, 'path': programming_path},
    }

    # Now, fonts for describing the icons. Rects and positions
    font = pygame.font.Font(join(FONTS_PATH, FONT_STYLE), 20)
    distros_font = font.render('Linux Distributions', True, WHITE)
    open_source_font = font.render('FLOSS', True, WHITE)
    programming_font = font.render('Programming Languages', True, WHITE)

    distros_rect = distros_font.get_rect()
    open_source_rect = open_source_font.get_rect()
    programming_rect = programming_font.get_rect()

    distros_rect.center = (left - 200, top + 50)
    open_source_rect.center = (left, top + 50)
    programming_rect.center = (left + 200, top + 50)

    SCREEN.blit(distros_font, distros_rect)
    SCREEN.blit(open_source_font, open_source_rect)
    SCREEN.blit(programming_font, programming_rect)

    return options


def reveal_box(board, row, col, box_img):
    """
    Revealed a box when it is clicked
    """
    rect = board['rects'][row][col]

    # Is it already revealed?
    if board['revealed'][row][col] == True:
        return

    # Play awesome sound
    sound_file = join(SOUNDS_PATH, 'reveal_box.wav')
    sound = pygame.mixer.Sound(sound_file)
    sound.play()

    animate_unrevealed(rect, box_img)

    # Mark box as revealed
    board['revealed'][row][col] = True
    SCREEN.blit(board['logos'][row][col], (rect.x, rect.y))
    pygame.display.update()


def all_matched(revealed_data):
    """
    Returns true if there are no signs of memory damage in your brain
    """
    for row in range(BOARD_ROWS):
        if False in revealed_data[row]:
            return False # Not yet buddy
    # No signs of Alzheimer
    return True


def get_logos_images(path):
    """
    Returns a shuffled list of logos images
    """
    logos = []

    for img in os.listdir(path):
        try:
            # Go Archie!
            logos.append(pygame.image.load(join(path, img)).convert_alpha())
        except pygame.error, e:
            continue
    random.shuffle(logos)

    return logos


def generate_board(logos_path, reveal=False):
    """
    Generate all the necessary data: the image logos, the rect that
    represents each image on the surface and the revealed data.
    Returns a dictionary containing all the information.
    """
    logos = [list() for r in range(BOARD_ROWS)]
    rects = [list() for r in range(BOARD_ROWS)]
    revealed = []

    # Get the logos images
    images = get_logos_images(logos_path)[:IMAGES_NEEDED]
    assert len(images) >= IMAGES_NEEDED, 'Not enough logos'
    images *= 2
    random.shuffle(images)

    x = X_MARGIN
    y = Y_MARGIN
    for row in range(BOARD_ROWS):
        for col in range(BOARD_COLS):
            rect = images[0].get_rect()
            rect.x = x
            rect.y = y
            rects[row].append(rect)
            logos[row].append(images[0])
            x += (BOX_SIZE + BOX_GAP)
            del images[0]
        x = X_MARGIN
        y += (BOX_SIZE + BOX_GAP)

    for i in range(BOARD_ROWS):
        revealed.append([reveal] * BOARD_COLS)

    # Everyday I'm shuffling
    random.shuffle(images)

    return {'logos': logos, 'rects': rects, 'revealed': revealed}


def draw_board(board, box_img):
    """
    Draw the board according to the current revealed state
    """
    for row in range(BOARD_ROWS):
        for col in range(BOARD_COLS):
            rect = board['rects'][row][col]
            x = rect.x
            y = rect.y
            if not board['revealed'][row][col]:
                SCREEN.blit(box_img, (x, y))
            else:
                SCREEN.blit(board['logos'][row][col], (x, y))


def draw_table(bg_color, border_color):
    margin = 20

    # Position and dimensions
    x = X_MARGIN - margin
    y = Y_MARGIN - margin
    width = BOARD_WIDTH + margin * 2
    height = BOARD_HEIGHT + margin * 2
    pygame.draw.rect(SCREEN, bg_color, (x, y, width, height))

    # Table border
    width = 5
    point_list = (
        (x, y),
        (x + BOARD_WIDTH + margin * 2, y),
        (x + BOARD_WIDTH + margin * 2, y + BOARD_HEIGHT + margin * 2),
        (x, y + BOARD_HEIGHT + margin * 2)
    )
    pygame.draw.polygon(SCREEN, BLACK, point_list, width)


if __name__ == '__main__':
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.