How to create a game for Pygame - Part 2 (Python)

Keywords : Sudoku, Dodger, 2048, Pygame, Game.


Demonstrating :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

Test, modify, correct, complete, improve and share your discoveries ! (!)


Sudoku

img_sudoku.png

   1 # sudoku.py
   2 
   3 """
   4 
   5 Author : Manoj_n
   6 https://www.geeksforgeeks.org/building-and-visualizing-sudoku-game-using-pygame/
   7 
   8 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
   9 
  10 """
  11 
  12 # import pygame library
  13 import pygame
  14 
  15 # initialise the pygame font
  16 pygame.font.init()
  17 
  18 #---------------------------------------------------------------------------
  19 
  20 # Total window
  21 screen = pygame.display.set_mode((500, 600))
  22 
  23 # Title and Icon
  24 pygame.display.set_caption("SUDOKU SOLVER USING BACKTRACKING")
  25 img = pygame.image.load('icon.png')
  26 pygame.display.set_icon(img)
  27 
  28 x = 0
  29 y = 0
  30 dif = 500 / 9
  31 val = 0
  32 # Default Sudoku Board.
  33 grid =[
  34         [7, 8, 0, 4, 0, 0, 1, 2, 0],
  35         [6, 0, 0, 0, 7, 5, 0, 0, 9],
  36         [0, 0, 0, 6, 0, 1, 0, 7, 8],
  37         [0, 0, 7, 0, 4, 0, 2, 6, 0],
  38         [0, 0, 1, 0, 5, 0, 9, 3, 0],
  39         [9, 0, 4, 0, 6, 0, 0, 0, 5],
  40         [0, 7, 0, 3, 0, 0, 0, 1, 2],
  41         [1, 2, 0, 0, 0, 7, 4, 0, 0],
  42         [0, 4, 9, 2, 0, 6, 0, 0, 7]
  43     ]
  44 
  45 #---------------------------------------------------------------------------
  46 
  47 # Load test fonts for future use
  48 font1 = pygame.font.SysFont("comicsans", 40)
  49 font2 = pygame.font.SysFont("comicsans", 20)
  50 def get_cord(pos):
  51     global x
  52     x = pos[0]//dif
  53     global y
  54     y = pos[1]//dif
  55 
  56 #---------------------------------------------------------------------------
  57 
  58 # Highlight the cell selected
  59 def draw_box():
  60     for i in range(2):
  61         pygame.draw.line(screen, (255, 0, 0), (x * dif-3, (y + i)*dif), (x * dif + dif + 3, (y + i)*dif), 7)
  62         pygame.draw.line(screen, (255, 0, 0), ( (x + i)* dif, y * dif ), ((x + i) * dif, y * dif + dif), 7)
  63 
  64 #---------------------------------------------------------------------------
  65 
  66 # Function to draw required lines for making Sudoku grid
  67 def draw():
  68     # Draw the lines
  69 
  70     for i in range (9):
  71         for j in range (9):
  72             if grid[i][j]!= 0:
  73 
  74                 # Fill blue color in already numbered grid
  75                 pygame.draw.rect(screen, (0, 153, 153), (i * dif, j * dif, dif + 1, dif + 1))
  76 
  77                 # Fill gird with default numbers specified
  78                 text1 = font1.render(str(grid[i][j]), 1, (0, 0, 0))
  79                 screen.blit(text1, (i * dif + 15, j * dif + 15))
  80     # Draw lines horizontally and verticallyto form grid
  81     for i in range(10):
  82         if i % 3 == 0 :
  83             thick = 7
  84         else:
  85             thick = 1
  86         pygame.draw.line(screen, (0, 0, 0), (0, i * dif), (500, i * dif), thick)
  87         pygame.draw.line(screen, (0, 0, 0), (i * dif, 0), (i * dif, 500), thick)
  88 
  89 #---------------------------------------------------------------------------
  90 
  91 # Fill value entered in cell
  92 def draw_val(val):
  93     text1 = font1.render(str(val), 1, (0, 0, 0))
  94     screen.blit(text1, (x * dif + 15, y * dif + 15))
  95 
  96 #---------------------------------------------------------------------------
  97 
  98 # Raise error when wrong value entered
  99 def raise_error1():
 100     text1 = font1.render("WRONG !!!", 1, (0, 0, 0))
 101     screen.blit(text1, (20, 570))
 102 
 103 #---------------------------------------------------------------------------
 104 
 105 # Raise error when wrong value entered
 106 def raise_error2():
 107     text1 = font1.render("Wrong !!! Not a valid Key", 1, (0, 0, 0))
 108     screen.blit(text1, (20, 570))
 109 
 110 #---------------------------------------------------------------------------
 111 
 112 # Check if the value entered in board is valid
 113 def valid(m, i, j, val):
 114     for it in range(9):
 115         if m[i][it]== val:
 116             return False
 117         if m[it][j]== val:
 118             return False
 119     it = i//3
 120     jt = j//3
 121     for i in range(it * 3, it * 3 + 3):
 122         for j in range (jt * 3, jt * 3 + 3):
 123             if m[i][j]== val:
 124                 return False
 125     return True
 126 
 127 #---------------------------------------------------------------------------
 128 
 129 # Solves the sudoku board using Backtracking Algorithm
 130 def solve(grid, i, j):
 131 
 132     while grid[i][j]!= 0:
 133         if i<8:
 134             i+= 1
 135         elif i == 8 and j<8:
 136             i = 0
 137             j+= 1
 138         elif i == 8 and j == 8:
 139             return True
 140     pygame.event.pump()
 141     for it in range(1, 10):
 142         if valid(grid, i, j, it)== True:
 143             grid[i][j]= it
 144             global x, y
 145             x = i
 146             y = j
 147             # white color background\
 148             screen.fill((255, 255, 255))
 149             draw()
 150             draw_box()
 151             pygame.display.update()
 152             pygame.time.delay(20)
 153             if solve(grid, i, j)== 1:
 154                 return True
 155             else:
 156                 grid[i][j]= 0
 157             # white color background\
 158             screen.fill((255, 255, 255))
 159 
 160             draw()
 161             draw_box()
 162             pygame.display.update()
 163             pygame.time.delay(50)
 164     return False
 165 
 166 #---------------------------------------------------------------------------
 167 
 168 # Display instruction for the game
 169 def instruction():
 170     text1 = font2.render("PRESS D TO RESET TO DEFAULT / R TO EMPTY", 1, (0, 0, 0))
 171     text2 = font2.render("ENTER VALUES AND PRESS ENTER TO VISUALIZE", 1, (0, 0, 0))
 172     screen.blit(text1, (20, 520))
 173     screen.blit(text2, (20, 540))
 174 
 175 #---------------------------------------------------------------------------
 176 
 177 # Display options when solved
 178 def result():
 179     text1 = font1.render("FINISHED PRESS R or D", 1, (0, 0, 0))
 180     screen.blit(text1, (20, 570))
 181 
 182 run = True
 183 flag1 = 0
 184 flag2 = 0
 185 rs = 0
 186 error = 0
 187 
 188 # The loop thats keep the window running
 189 while run:
 190 
 191     # White color background
 192     screen.fill((255, 255, 255))
 193     # Loop through the events stored in event.get()
 194     for event in pygame.event.get():
 195         # Quit the game window
 196         if event.type == pygame.QUIT:
 197             run = False
 198         # Get the mouse postion to insert number
 199         if event.type == pygame.MOUSEBUTTONDOWN:
 200             flag1 = 1
 201             pos = pygame.mouse.get_pos()
 202             get_cord(pos)
 203         # Get the number to be inserted if key pressed
 204         if event.type == pygame.KEYDOWN:
 205             if event.key == pygame.K_LEFT:
 206                 x-= 1
 207                 flag1 = 1
 208             if event.key == pygame.K_RIGHT:
 209                 x+= 1
 210                 flag1 = 1
 211             if event.key == pygame.K_UP:
 212                 y-= 1
 213                 flag1 = 1
 214             if event.key == pygame.K_DOWN:
 215                 y+= 1
 216                 flag1 = 1
 217             if event.key == pygame.K_1:
 218                 val = 1
 219             if event.key == pygame.K_2:
 220                 val = 2
 221             if event.key == pygame.K_3:
 222                 val = 3
 223             if event.key == pygame.K_4:
 224                 val = 4
 225             if event.key == pygame.K_5:
 226                 val = 5
 227             if event.key == pygame.K_6:
 228                 val = 6
 229             if event.key == pygame.K_7:
 230                 val = 7
 231             if event.key == pygame.K_8:
 232                 val = 8
 233             if event.key == pygame.K_9:
 234                 val = 9
 235             if event.key == pygame.K_RETURN:
 236                 flag2 = 1
 237             # If R pressed clear the sudoku board
 238             if event.key == pygame.K_r:
 239                 rs = 0
 240                 error = 0
 241                 flag2 = 0
 242                 grid =[
 243                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 244                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 245                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 246                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 247                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 248                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 249                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 250                 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 251                 [0, 0, 0, 0, 0, 0, 0, 0, 0]
 252                 ]
 253             # If D is pressed reset the board to default
 254             if event.key == pygame.K_d:
 255                 rs = 0
 256                 error = 0
 257                 flag2 = 0
 258                 grid =[
 259                     [7, 8, 0, 4, 0, 0, 1, 2, 0],
 260                     [6, 0, 0, 0, 7, 5, 0, 0, 9],
 261                     [0, 0, 0, 6, 0, 1, 0, 7, 8],
 262                     [0, 0, 7, 0, 4, 0, 2, 6, 0],
 263                     [0, 0, 1, 0, 5, 0, 9, 3, 0],
 264                     [9, 0, 4, 0, 6, 0, 0, 0, 5],
 265                     [0, 7, 0, 3, 0, 0, 0, 1, 2],
 266                     [1, 2, 0, 0, 0, 7, 4, 0, 0],
 267                     [0, 4, 9, 2, 0, 6, 0, 0, 7]
 268                 ]
 269     if flag2 == 1:
 270         if solve(grid, 0, 0)== False:
 271             error = 1
 272         else:
 273             rs = 1
 274         flag2 = 0
 275     if val != 0:
 276         draw_val(val)
 277         # print(x)
 278         # print(y)
 279         if valid(grid, int(x), int(y), val)== True:
 280             grid[int(x)][int(y)]= val
 281             flag1 = 0
 282         else:
 283             grid[int(x)][int(y)]= 0
 284             raise_error2()
 285         val = 0
 286 
 287     if error == 1:
 288         raise_error1()
 289     if rs == 1:
 290         result()
 291     draw()
 292     if flag1 == 1:
 293         draw_box()
 294     instruction()
 295 
 296     # Update window
 297     pygame.display.update()
 298 
 299 #---------------------------------------------------------------------------
 300 
 301 # Quit pygame window
 302 pygame.quit()


Dodger

img_dodger.png

   1 # dodger.py
   2 
   3 """
   4 
   5 Author : Thelost
   6 Link : http://hk.uwenku.com/question/p-vlutvuiu-hb.html
   7 
   8 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
   9 
  10 """
  11 
  12 import sys
  13 import pygame
  14 import random
  15 
  16 #---------------------------------------------------------------------------
  17 
  18 WINDOWWIDTH = 600
  19 WINDOWHEIGHT = 600
  20 TEXTCOLOR = (255, 255, 255)
  21 BACKGROUNDCOLOR = (0, 0, 0)
  22 FPS = 40
  23 BADDIEMINSIZE = 10
  24 BADDIEMAXSIZE = 40
  25 BADDIEMINSPEED = 1
  26 BADDIEMAXSPEED = 8
  27 ADDNEWBADDIERATE = 6
  28 PLAYERMOVERATE = 5
  29 
  30 #---------------------------------------------------------------------------
  31 
  32 def terminate():
  33     pygame.quit()
  34     sys.exit()
  35 
  36 #---------------------------------------------------------------------------
  37 
  38 def waitForPlayerToPressKey():
  39     while True:
  40      for event in pygame.event.get():
  41       if event.type == pygame.QUIT:
  42        terminate()
  43       if event.type == pygame.KEYDOWN:
  44        if event.key == pygame.K_ESCAPE: # pressing escape quits
  45         terminate()
  46        return
  47 
  48 #---------------------------------------------------------------------------
  49 
  50 def playerHasHitBaddie(playerRect, baddies):
  51     for b in baddies:
  52      if playerRect.colliderect(b['rect']):
  53       return True
  54     return False
  55 
  56 #---------------------------------------------------------------------------
  57 
  58 def drawText(text, font, surface, x, y):
  59     textobj = font.render(text, 1, TEXTCOLOR)
  60     textrect = textobj.get_rect()
  61     textrect.topleft = (x, y)
  62     surface.blit(textobj, textrect)
  63 
  64 #---------------------------------------------------------------------------
  65 
  66 # set up pygame, the window, and the mouse cursor
  67 pygame.init()
  68 mainClock = pygame.time.Clock()
  69 windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
  70 pygame.display.set_caption('Dodger')
  71 pygame.mouse.set_visible(False)
  72 
  73 # set up fonts
  74 font = pygame.font.SysFont(None, 48)
  75 
  76 # set up sounds
  77 
  78 # set up images
  79 playerImage = pygame.image.load('player.png')
  80 playerRect = playerImage.get_rect()
  81 baddieImage = pygame.image.load('bad.png')
  82 
  83 # show the "Start" screen
  84 drawText('Dodger', font, windowSurface, (WINDOWWIDTH/3), (WINDOWHEIGHT/3))
  85 drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH/3) - 30, (WINDOWHEIGHT/3) + 50)
  86 pygame.display.update()
  87 waitForPlayerToPressKey()
  88 
  89 #---------------------------------------------------------------------------
  90 
  91 topScore = 0
  92 while True:
  93     # set up the start of the game
  94     baddies = []
  95     score = 0
  96     playerRect.topleft = (WINDOWWIDTH/2, WINDOWHEIGHT - 50)
  97     moveLeft = moveRight = moveUp = moveDown = False
  98     reverseCheat = slowCheat = False
  99     baddieAddCounter = 0
 100 
 101     while True: # the game loop runs while the game part is playing
 102      score += 1 # increase score
 103 
 104      for event in pygame.event.get():
 105       if event.type == pygame.QUIT:
 106        terminate()
 107 
 108       if event.type == pygame.KEYDOWN:
 109        if event.key == ord('z'):
 110         reverseCheat = True
 111        if event.key == ord('x'):
 112         slowCheat = True
 113        if event.key == pygame.K_LEFT or event.key == ord('a'):
 114         moveRight = False
 115         moveLeft = True
 116        if event.key == pygame.K_RIGHT or event.key == ord('d'):
 117         moveLeft = False
 118         moveRight = True
 119        if event.key == pygame.K_UP or event.key == ord('w'):
 120         moveDown = False
 121         moveUp = True
 122        if event.key == pygame.K_DOWN or event.key == ord('s'):
 123         moveUp = False
 124         moveDown = True
 125 
 126       if event.type == pygame.KEYUP:
 127        if event.key == ord('z'):
 128         reverseCheat = False
 129         score = 0
 130        if event.key == ord('x'):
 131         slowCheat = False
 132         score = 0
 133        if event.key == pygame.K_ESCAPE:
 134          terminate()
 135 
 136        if event.key == pygame.K_LEFT or event.key == ord('a'):
 137         moveLeft = False
 138        if event.key == pygame.K_RIGHT or event.key == ord('d'):
 139         moveRight = False
 140        if event.key == pygame.K_UP or event.key == ord('w'):
 141         moveUp = False
 142        if event.key == pygame.K_DOWN or event.key == ord('s'):
 143         moveDown = False
 144 
 145       if event.type == pygame.MOUSEMOTION:
 146        # If the mouse moves, move the player where the cursor is.
 147        playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
 148 
 149      # Add new baddies at the top of the screen, if needed.
 150      if not reverseCheat and not slowCheat:
 151       baddieAddCounter += 1
 152      if baddieAddCounter == ADDNEWBADDIERATE:
 153       baddieAddCounter = 0
 154       baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
 155       newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
 156          'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
 157          'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
 158          }
 159 
 160       baddies.append(newBaddie)
 161 
 162      # Move the player around.
 163      if moveLeft and playerRect.left > 0:
 164       playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
 165      if moveRight and playerRect.right < WINDOWWIDTH:
 166       playerRect.move_ip(PLAYERMOVERATE, 0)
 167      if moveUp and playerRect.top > 0:
 168       playerRect.move_ip(0, -1 * PLAYERMOVERATE)
 169      if moveDown and playerRect.bottom < WINDOWHEIGHT:
 170       playerRect.move_ip(0, PLAYERMOVERATE)
 171 
 172      # Move the mouse cursor to match the player.
 173      pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
 174 
 175      # Move the baddies down.
 176      for b in baddies:
 177       if not reverseCheat and not slowCheat:
 178        b['rect'].move_ip(0, b['speed'])
 179       elif reverseCheat:
 180        b['rect'].move_ip(0, -5)
 181       elif slowCheat:
 182        b['rect'].move_ip(0, 1)
 183 
 184      # Delete baddies that have fallen past the bottom.
 185      for b in baddies[:]:
 186       if b['rect'].top > WINDOWHEIGHT:
 187        baddies.remove(b)
 188 
 189      # Draw the game world on the window.
 190      windowSurface.fill(BACKGROUNDCOLOR)
 191 
 192      # Draw the score and top score.
 193      drawText('Score: %s' % (score), font, windowSurface, 10, 0)
 194      drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
 195 
 196      # Draw the player's rectangle
 197      windowSurface.blit(playerImage, playerRect)
 198 
 199      # Draw each baddie
 200      for b in baddies:
 201       windowSurface.blit(b['surface'], b['rect'])
 202 
 203      pygame.display.update()
 204 
 205      # Check if any of the baddies have hit the player.
 206      if playerHasHitBaddie(playerRect, baddies):
 207       if score > topScore:
 208        topScore = score # set new top score
 209       break
 210 
 211      mainClock.tick(FPS)
 212 
 213     # Stop the game and show the "Game Over" screen.
 214 
 215     drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH/3), (WINDOWHEIGHT/3))
 216     drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH/3) - 80, (WINDOWHEIGHT/3) + 50)
 217     pygame.display.update()
 218     waitForPlayerToPressKey()


2048

img_2048.png

   1 # -*- coding : utf-8 -*-
   2 
   3 # 2048.py
   4 
   5 """
   6 
   7 Author : DarkSoul
   8 Link : https://www.cnblogs.com/darksouls/p/8227821.html
   9 
  10 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
  11 
  12 """
  13 
  14 import numpy,sys,random,pygame
  15 from pygame.locals import*
  16 
  17 #---------------------------------------------------------------------------
  18 
  19 Size = 4                                          #4*4行列
  20 Block_WH = 110                                    #每个块的长度宽度
  21 BLock_Space = 10                                  #两个块之间的间隙
  22 Block_Size = Block_WH*Size+(Size+1)*BLock_Space
  23 Matrix = numpy.zeros([Size,Size])                 #初始化矩阵4*4的0矩阵
  24 Screen_Size = (Block_Size,Block_Size+110)
  25 Title_Rect = pygame.Rect(0,0,Block_Size,110)      #设置标题矩形的大小
  26 Score = 0
  27 
  28 Block_Color = {
  29         0:(150,150,150),
  30         2:(255,255,255),
  31         4:(255,255,128),
  32         8:(255,255,0),
  33         16:(255,220,128),
  34         32:(255,220,0),
  35         64:(255,190,0),
  36         128:(255,160,0),
  37         256:(255,130,0),
  38         512:(255,100,0),
  39         1024:(255,70,0),
  40         2048:(255,40,0),
  41         4096:(255,10,0),
  42 }                                                     #数块颜色
  43 
  44 #---------------------------------------------------------------------------
  45 
  46 #基础类
  47 class UpdateNew(object):
  48         """docstring for UpdateNew"""
  49         def __init__(self,matrix):
  50                 super(UpdateNew, self).__init__()
  51                 self.matrix = matrix
  52                 self.score  = 0
  53                 self.zerolist = []
  54 
  55         def combineList(self,rowlist):
  56                 start_num = 0
  57                 end_num = Size-rowlist.count(0)-1
  58                 while start_num < end_num:
  59                         if rowlist[start_num] == rowlist[start_num+1]:
  60                                 rowlist[start_num] *= 2
  61                                 self.score += int(rowlist[start_num])                      #每次返回累加的分数
  62                                 rowlist[start_num+1:] = rowlist[start_num+2:]
  63                                 rowlist.append(0)
  64                         start_num += 1
  65                 return rowlist
  66 
  67         def removeZero(self,rowlist):
  68                 while True:
  69                         mid = rowlist[:]                      #拷贝一份list
  70                         try:
  71                                 rowlist.remove(0)
  72                                 rowlist.append(0)
  73                         except:
  74                                 pass
  75                         if rowlist == mid:
  76                                 break;
  77                 return self.combineList(rowlist)
  78 
  79         def toSequence(self,matrix):
  80                 lastmatrix = matrix.copy()
  81                 m,n = matrix.shape                                         #获得矩阵的行,列
  82                 for i in range(m):
  83                         newList = self.removeZero(list(matrix[i]))
  84                         matrix[i] = newList
  85                         for k in range(Size-1,Size-newList.count(0)-1,-1):     #添加所有有0的行号列号
  86                                 self.zerolist.append((i,k))
  87                 if matrix.min() == 0 and (matrix!=lastmatrix).any():       #矩阵中有最小值0且移动后的矩阵不同,才可以添加0位置处添加随机数
  88                         GameInit.initData(Size,matrix,self.zerolist)
  89                 return matrix
  90 
  91 #---------------------------------------------------------------------------
  92 
  93 class LeftAction(UpdateNew):
  94         """docstring for LeftAction"""
  95         def __init__(self,matrix):
  96                 super(LeftAction, self).__init__(matrix)
  97 
  98         def handleData(self):
  99                 matrix = self.matrix.copy()                               #获得一份矩阵的复制
 100                 newmatrix = self.toSequence(matrix)
 101                 return newmatrix,self.score
 102 
 103 #---------------------------------------------------------------------------
 104 
 105 class RightAction(UpdateNew):
 106         """docstring for RightAction"""
 107         def __init__(self,matrix):
 108                 super(RightAction, self).__init__(matrix)
 109 
 110         def handleData(self):
 111                 matrix = self.matrix.copy()[:,::-1]
 112                 newmatrix = self.toSequence(matrix)
 113                 return newmatrix[:,::-1],self.score
 114 
 115 #---------------------------------------------------------------------------
 116 
 117 class UpAction(UpdateNew):
 118         """docstring for UpAction"""
 119         def __init__(self,matrix):
 120                 super(UpAction, self).__init__(matrix)
 121 
 122         def handleData(self):
 123                 matrix = self.matrix.copy().T
 124                 newmatrix = self.toSequence(matrix)
 125                 return newmatrix.T,self.score
 126 
 127 #---------------------------------------------------------------------------
 128 
 129 class DownAction(UpdateNew):
 130         """docstring for DownAction"""
 131         def __init__(self,matrix):
 132                 super(DownAction, self).__init__(matrix)
 133 
 134         def handleData(self):
 135                 matrix = self.matrix.copy()[::-1].T
 136                 newmatrix = self.toSequence(matrix)
 137                 return newmatrix.T[::-1],self.score
 138 
 139 #---------------------------------------------------------------------------
 140 
 141 class GameInit(object):
 142         """docstring for GameInit"""
 143         def __init__(self):
 144                 super(GameInit, self).__init__()
 145 
 146         @staticmethod
 147         def getRandomLocal(zerolist = None):
 148                 if zerolist == None:
 149                         a = random.randint(0,Size-1)
 150                         b = random.randint(0,Size-1)
 151                 else:
 152                         a,b = random.sample(zerolist,1)[0]
 153                 return a,b
 154 
 155         @staticmethod
 156         def getNewNum():                             #随机返回2或者4
 157                 n = random.random()
 158                 if n > 0.8:
 159                         n = 4
 160                 else:
 161                         n = 2
 162                 return n
 163 
 164 
 165         @classmethod
 166         def initData(cls,Size,matrix = None,zerolist = None):
 167                 if matrix is None:
 168                         matrix = Matrix.copy()
 169                 a,b = cls.getRandomLocal(zerolist)       #zerolist空任意返回(x,y)位置,否则返回任意一个0元素位置
 170                 n = cls.getNewNum()
 171                 matrix[a][b] = n
 172                 return matrix                           #返回初始化任意位置为2或者4的矩阵
 173 
 174         @classmethod
 175         def drawSurface(cls,screen,matrix,score):
 176                 pygame.draw.rect(screen,(255,255,255),Title_Rect)              #第一个参数是屏幕,第二个参数颜色,第三个参数rect大小,第四个默认参数
 177                 font1 = pygame.font.SysFont('simsun',48)
 178                 font2 = pygame.font.SysFont(None,32)
 179                 screen.blit(font1.render('Score:',True,(255,127,0)),(20,25))     #font.render第一个参数是文本内容,第二个参数是否抗锯齿,第三个参数字体颜色
 180                 screen.blit(font1.render('%s' % score,True,(255,127,0)),(170,25))
 181                 screen.blit(font2.render('up',True,(255,127,0)),(360,20))
 182                 screen.blit(font2.render('left  down  right',True,(255,127,0)),(300,50))
 183                 a,b = matrix.shape
 184                 for i in range(a):
 185                         for j in range(b):
 186                                 cls.drawBlock(screen,i,j,Block_Color[matrix[i][j]],matrix[i][j])
 187 
 188 
 189         @staticmethod
 190         def drawBlock(screen,row,column,color,blocknum):
 191                 font = pygame.font.SysFont('stxingkai',80)
 192                 w = column*Block_WH+(column+1)*BLock_Space
 193                 h = row*Block_WH+(row+1)*BLock_Space+110
 194                 pygame.draw.rect(screen,color,(w,h,110,110))
 195                 if blocknum != 0:
 196                         fw,fh = font.size(str(int(blocknum)))
 197                         screen.blit(font.render(str(int(blocknum)),True,(0,0,0)),(w+(110-fw)/2,h+(110-fh)/2))
 198 
 199         @staticmethod
 200         def keyDownPressed(keyvalue,matrix):
 201                 if keyvalue == K_LEFT:
 202                         return LeftAction(matrix)
 203                 elif keyvalue == K_RIGHT:
 204                         return RightAction(matrix)
 205                 elif keyvalue == K_UP:
 206                         return UpAction(matrix)
 207                 elif keyvalue == K_DOWN:
 208                         return DownAction(matrix)
 209 
 210         @staticmethod
 211         def gameOver(matrix):
 212                 testmatrix = matrix.copy()
 213                 a,b = testmatrix.shape
 214                 for i in range(a):
 215                         for j in range(b-1):
 216                                 if testmatrix[i][j] == testmatrix[i][j+1]:                    #如果每行存在相邻两个数相同,则游戏没有结束
 217                                         print('游戏没有结束')
 218                                         return False
 219                 for i in range(b):
 220                         for j in range(a-1):
 221                                 if testmatrix[j][i] == testmatrix[j+1][i]:
 222                                         print('游戏没有结束')
 223                                         return False
 224                 print('游戏结束')
 225                 return True
 226 
 227 #---------------------------------------------------------------------------
 228 
 229 def main():
 230         pygame.init()
 231         screen = pygame.display.set_mode(Screen_Size,0,32)      #屏幕设置
 232         pygame.display.set_caption('2048')
 233         matrix = GameInit.initData(Size)
 234         currentscore = 0
 235         GameInit.drawSurface(screen,matrix,currentscore)
 236         pygame.display.update()
 237         while True:
 238                 for event in pygame.event.get():
 239                         if event.type == pygame.KEYDOWN:
 240                                 if event.key == pygame.K_ESCAPE: # pressing escape quits
 241                                         pygame.quit()
 242                                         return
 243                         if event.type == pygame.QUIT:
 244                                 pygame.quit()
 245                                 sys.exit(0)
 246                         elif event.type == pygame.KEYDOWN:
 247                                 actionObject = GameInit.keyDownPressed(event.key,matrix)     #创建各种动作类的对象
 248                                 matrix,score = actionObject.handleData()                     #处理数据
 249                                 currentscore += score
 250                                 GameInit.drawSurface(screen,matrix,currentscore)
 251                                 if matrix.min() != 0:
 252                                         GameInit.gameOver(matrix)
 253 
 254                 pygame.display.update()
 255 
 256 #---------------------------------------------------------------------------
 257 
 258 if __name__ == '__main__':
 259         main()


Download source

source.zip


Additional Information

Link :

https://wiki.python.org/moin/GameProgramming

http://mientki.ruhosting.nl/data_www/pylab_works/pw_bricks_2d_scene.html

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Manoj_n (sudoku.py coding), Thelost (dodger.py coding), Dark Soulz (2048.py coding), the Pygame community...


About this page

Date(d/m/y) Person (bot) Comments :

19/09/20 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah...

How to create a game for Pygame - Part 2 (Python) (last edited 2020-10-25 16:47:01 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.