pygame 러시아 블록 게임 실현

20073 단어 pygame러시아 블록
본 논문 의 사례 는 pygame 이 러시아 블록 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.

import random, time, pygame, sys
from pygame.locals import *

FPS = 25
WINDOWWIDTH = 640#        
WINDOWHEIGHT = 480#        
BOXSIZE = 20#         
BOARDWIDTH = 10#       10      
BOARDHEIGHT = 20#       20      
BLANK = '.'#      

#                 ,                     。  ,                                 。
MOVESIDEWAYSFREQ = 0.15 #                    0.15    ,           
MOVEDOWNFREQ = 0.1  #             0.1    ,        
XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2)#(0INDOWWIDTH       -            *       )/2             
TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5#TOPMARGIN:            =      -(            *       )-5
#    R G B
WHITE  = (255, 255, 255)#  
GRAY  = (185, 185, 185)#  
BLACK  = ( 0, 0, 0)#  
RED   = (155, 0, 0)#  
GREEN  = ( 0, 155, 0)#  
BLUE  = ( 0, 0, 155)#  
YELLOW  = (155, 155, 0)#  
BORDERCOLOR = BLUE#    
BGCOLOR = BLACK#    
TEXTCOLOR = WHITE#    
COLORS  = (BLUE,GREEN,RED,YELLOW) #      ,  COLORS   
TEMPLATEWIDTH = 5#      
TEMPLATEHEIGHT = 5#     

S_SHAPE_TEMPLATE = [['.....', #S     
      '.....',
      '..OO.',
      '.OO..',
      '.....'],
     ['.....', #S        
      '..O..',
      '..OO.',
      '...O.',
      '.....']]

Z_SHAPE_TEMPLATE = [['.....', #Z   
      '.....',
      '.OO..',
      '..OO.',
      '.....'],
     ['.....',
      '..O..',
      '.OO..',
      '.O...',
      '.....']]

I_SHAPE_TEMPLATE = [['..O..', #I   
      '..O..',
      '..O..',
      '..O..',
      '.....'],
     ['.....',
      '.....',
      'OOOO.',
      '.....',
      '.....']]

O_SHAPE_TEMPLATE = [['.....', #O   
      '.....',
      '.OO..',
      '.OO..',
      '.....']]

J_SHAPE_TEMPLATE = [['.....', #J   
      '.O...',
      '.OOO.',
      '.....',
      '.....'],
     ['.....',
      '..OO.',
      '..O..',
      '..O..',
      '.....'],
     ['.....',
      '.....',
      '.OOO.',
      '...O.',
      '.....'],
     ['.....',
      '..O..',
      '..O..',
      '.OO..',
      '.....']]

L_SHAPE_TEMPLATE = [['.....', #L   
      '...O.',
      '.OOO.',
      '.....',
      '.....'],
     ['.....',
      '..O..',
      '..O..',
      '..OO.',
      '.....'],
     ['.....',
      '.....',
      '.OOO.',
      '.O...',
      '.....'],
     ['.....',
      '.OO..',
      '..O..',
      '..O..',
      '.....']]

T_SHAPE_TEMPLATE = [['.....', #T   
      '..O..',
      '.OOO.',
      '.....',
      '.....'],
     ['.....',
      '..O..',
      '..OO.',
      '..O..',
      '.....'],
     ['.....',
      '.....',
      '.OOO.',
      '..O..',
      '.....'],
     ['.....',
      '..O..',
      '.OO..',
      '..O..',
      '.....']]

PIECES = {'S': S_SHAPE_TEMPLATE, #PIECES     ,           (  )。                  (  )。
   'Z': Z_SHAPE_TEMPLATE,
   'J': J_SHAPE_TEMPLATE,
   'L': L_SHAPE_TEMPLATE,
   'I': I_SHAPE_TEMPLATE,
   'O': O_SHAPE_TEMPLATE,
   'T': T_SHAPE_TEMPLATE}

def main(): #main()                 ,                    。
 global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT
 pygame.init()# inport pygame                   
 FPSCLOCK = pygame.time.Clock()#pygame.time.Clock()  pygame.time.Clock  
 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) #pygame.display.set_mode()        ,         ,
 # :        ,     ,     pygame.Surface  
 BASICFONT = pygame.font.Font('freesansbold.ttf', 18)#  
 BIGFONT = pygame.font.Font('freesansbold.ttf', 100)#  
 pygame.display.set_caption('Tetromino')#      
 showTextScreen('Tetromino')#            

 while True: #    ,                          ,  :         
  pygame.mixer.music.load('tetrisc.mp3')#     
  pygame.mixer.music.play(-1, 0.0)#    
  runGame()#  runGame()    ,        ,runGame()   main(),
  pygame.mixer.music.stop()#  main()       
  showTextScreen('Game Over')#         。        ,showTextScreen()     ,    main()      ,      

def runGame():#         runGame 
#              ,                     。
 board = getBlankBoard()#             
 lastMoveDownTime = time.time()#lastMoveDownTime           
 lastMoveSidewaysTime = time.time()#lastMoveSidewaysTime          
 lastFallTime = time.time()#         
 movingDown = False #         
 movingLeft = False #         
 movingRight = False #         
 score = 0 #  
 level, fallFreq = calculateLevelAndFallFreq(score)#          ,    score=0,      level=1,fallFreq=0.25
 fallingPiece = getNewPiece() #fallingPiece                     
 nextPiece = getNewPiece() #nextPice     Next       ,           

 while True: #      ,              ,         
  if fallingPiece == None:#            ,fallingPiece     None
   fallingPiece = nextPiece#    nextPiece         fallingPiece 。
   nextPiece = getNewPiece()#      nextPiece  ,      getNewPiece()    。
   lastFallTime = time.time() #             ,       fallFreq             。
   if not isValidPosition(board, fallingPiece):
     #  ,          ,isValidPosition()   False,           ,  ,            ,     。
    return #       runGame()      。

  for event in pygame.event.get(): #                 ,       。
    #          movingLeft movingRight movingDown     False,       
    #           。           “moving”    Boolean       。
   if event.type == KEYUP:#          KEYUP  
    if (event.key == K_LEFT):#                
     movingLeft = False #     False,                  。
    elif (event.key == K_RIGHT):#  
     movingRight = False
    elif (event.key == K_DOWN):#  
     movingDown = False

   elif event.type == KEYDOWN:#          KEYDOWN  
    if (event.key == K_LEFT) and isValidPosition(board, fallingPiece, adjX=-1):
    #            ,            
     fallingPiece['x'] = fallingPiece['x'] -1 #  
     movingLeft = True # movingLeft     True,                     
     movingRight = False #  movingRight   False
     lastMoveSidewaysTime = time.time() #lastMoveSidewaysTime       
#    movingLeft,movingRigh                    。  movingLeft     True,                      。

    elif (event.key == K_RIGHT ) and isValidPosition(board, fallingPiece, adjX=1): #  
     fallingPiece['x'] =fallingPiece['x'] + 1
     movingRight = True
     movingLeft = False
     lastMoveSidewaysTime = time.time()

    #                   。         fallingPiece    'rotation'     1。  ,    'rotation'   
    #        ,              (   len(PIECES[fallingPiece['shape']   )    ,  ,        0  。
    elif event.key == K_UP :
     fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
     if not isValidPosition(board, fallingPiece):
     #                                 ,  ,
     #       fallingPiece['rotation']  1         。       len(PIECES[fallingPiece['shape']])   
     # ,        -1,                。????
      fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])

    #        ,                    。
    elif (event.key == K_DOWN ):
     movingDown = True # movingDown   True
     if isValidPosition(board, fallingPiece, adjY=1):#       
      fallingPiece['y'] = fallingPiece['y'] +1 #  
     lastMoveDownTime = time.time() #lastMoveDownTime         。         ,               ,   
     #         

  if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:#MOVESIDEWAYSFREQ = 0.15         0.15 
   if movingLeft and isValidPosition(board, fallingPiece, adjX=-1):#        ,          
    fallingPiece['x'] =fallingPiece['x'] - 1#       
   elif movingRight and isValidPosition(board, fallingPiece, adjX=1):#        ,          
    fallingPiece['x'] =fallingPiece['x'] + 1#       
   lastMoveSidewaysTime = time.time() # lastMoveSidewaysTime       。

  if movingDown and time.time() - lastMoveDownTime > MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1):
  #MOVEDOWNFREQ = 0.1         0.1 ,          
   fallingPiece['y'] = fallingPiece['y'] + 1#        
   lastMoveDownTime = time.time()# laslastMoveDownTime       。

  #       
  if time.time() - lastFallTime > fallFreq:#fallFreq       
   if not isValidPosition(board, fallingPiece, adjY=1):#           ,            。
    addToBoard(board, fallingPiece) #                  
    score=score + removeCompleteLines(board)# removeCompleteLines()                    ,         。
    #removeCompleteLines()           ,        ,              。
    level, fallFreq = calculateLevelAndFallFreq(score)#         ,    calculateLevelAndFallFreq()                   。
    fallingPiece = None#     fallingPiece     None,                  ,                     。??????
   else:
    #         ,      Y          ,   lastFallTime       
    fallingPiece['y'] = fallingPiece['y'] +1
    lastFallTime = time.time()

  # drawing everything on the screen
  DISPLAYSURF.fill(BGCOLOR)
  drawBoard(board)
  drawStatus(score, level)
  drawNextPiece(nextPiece)
  if fallingPiece != None:#         
   drawPiece(fallingPiece)
  pygame.display.update()
  FPSCLOCK.tick(FPS)

def makeTextObjs(text, font, color):
 surf = font.render(text, True, color)
 return surf, surf.get_rect()

def checkForKeyPress():
 # checkForKeyPress()     Wormy          。  ,   checkForQuit()      QUIT  (       Esc  KEYUP  ),          
 #      。  ,             KEYDOWN, KEYUP  。        KEYDOWN  (  pygame.event.get()   KEYDOWN,               )。
 #         KEYUP  ,       None。
 for event in pygame.event.get([KEYDOWN, KEYUP]):
  if event.type == KEYDOWN:
   continue
  return event.key
 return None

def calculateLevelAndFallFreq(score):#        ,       1 。   10 ,          ,        。              
 level = int(score / 10) + 1 #           。     ,    int()     10     。       0-9       ,int()     
 fallFreq = 0.27 - (level * 0.02) #   0。     +1  ,                 ,    0 。     10    ,int(10/10)     1
 return level, fallFreq #  +1        2
 #         ,          0.27(     0.27 ,          )。  ,        0.02,       0.27    。  ,    1,
 #   0.27   0.02*1  0.25。   2     0.02*2  0.23。         ,                0.02 。

#getNewPiece()           ,         (  'y'=-2)。
def getNewPiece():
 shape = random.choice(list(PIECES.keys()))#PIECES     ,           ,             (     )。
 #PIECES.keys()    (['Z','J','L','I','O','T'])   ,list(PIECES.keys())    ['Z','J','L','I','O','T']  
 #       random.choice()             。 random.choice()               ,    'Z'。
 newPiece = {'shape': shape,
    'rotation': random.randint(0, len(PIECES[shape]) - 1), #rotation:               
    #PIECES['Z']     [[  ],[  ]],len(PIECES['z'])     2 2-1=1 random.randint(0,1)     [0,1]
    'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), #'x'    5x5                ,               。
    'y': -2, #'x'    5x5                ,'y'         -2               (       0 )
    'color': random.randint(0, len(COLORS) - 1)#COLORS:         
    }
 return newPiece#getNewPiece()    newPiece  

#            
def addToBoard(board, piece): #                  。                   ,                     
 for x in range(TEMPLATEWIDTH): #               
  for y in range(TEMPLATEHEIGHT):#  for   5x5      ,          ,         
   if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:
    board[x + piece['x']][y + piece['y']] = piece['color'] #              :  (      ),'.'   ,          

def getBlankBoard(): #             。
 board = [] #          
 for i in range(BOARDWIDTH):# range(10)=[0,9] BOARDWIDTH=10 BLANK = '.' #      
  board.append([BLANK] * BOARDHEIGHT)
 #board[0]-board[9]         20 .      
 return board

def isOnBoard(x, y):#isOnBoard()      x,y           
 return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT#BOARDWIDTH=10,BOARDHEIGHT=20

def isValidPosition(board, piece, adjX=0, adjY=0):#board:    piece:   adjX,adjY  5x5          
#isValidPositio,n()                               ,    True
#isValidPosition()      adjX adjY     。  ,isValidPosition()                          (  adjX=0, adjY=0)。
#  ,                 ,               
##   adjX -1.                      ,                        。
# adjX  1  ,             。       adjY  。  -1 adjY,                   ,
#  adjY   3             3   。
 for x in range(TEMPLATEWIDTH): #TEMPLATEWIDTH=5 TEMPLATEWIDTH=5
  for y in range(TEMPLATEHEIGHT):#            
   isAboveBoard = y + piece['y'] + adjY < 0 #           
   if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK:# 5x5      '.'   ,     
    continue
   if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):#          
    return False
   if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:#              
    return False
 return True

def isCompleteLine(board, y):#  y     ,    True
 for x in range(BOARDWIDTH):#         
  if board[x][y] == BLANK:#      ,    
   return False
 return True

def removeCompleteLines(board):#       ,                         。       
 numLinesRemoved = 0
 y = BOARDHEIGHT - 1 # BOARDHEIGHT=20-1=19       
 while y >= 0:#        y     ,                 
  if isCompleteLine(board, y):#      
   for pullDownY in range(y, 0, -1): #range(y, 0, -1)  [y,1]
    for x in range(BOARDWIDTH):
     board[x][pullDownY] = board[x][pullDownY-1]#                    
   for x in range(BOARDWIDTH):#     
    board[x][0]=BLANK
   numLinesRemoved=numLinesRemoved+1
  else:
   y =y- 1 #     
 return numLinesRemoved

def convertToPixelCoords(boxx, boxy):#                 
 return (XMARGIN + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))#XMARGIN           ,TOPMARGIN           

def drawBoard(board):#       
 pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN - 3, TOPMARGIN - 7, (BOARDWIDTH * BOXSIZE) + 8, (BOARDHEIGHT * BOXSIZE) + 8), 5)
 #pygame.draw.rect(DISPLAYSURF  ,RED  ,(x,y,width,height),    ) rect:   x,y         width        height    
 #     0(  )      , 1      
 pygame.draw.rect(DISPLAYSURF, BGCOLOR, (XMARGIN, TOPMARGIN, BOXSIZE * BOARDWIDTH, BOXSIZE * BOARDHEIGHT)) #          
 for x in range(BOARDWIDTH):#     
  for y in range(BOARDHEIGHT):
   drawBox(x, y, board[x][y])#                

#             (          )
def drawBox(boxx, boxy, color, pixelx=None, pixely=None):#        
 if color == BLANK: #           ,  5x5    
  return
 if pixelx == None and pixely == None:
  pixelx, pixely = convertToPixelCoords(boxx, boxy)#                 
 pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 1, BOXSIZE - 1))#  1     ,              
 #     ,              。

#      
def drawPiece(piece, pixelx=None, pixely=None):#pixelx, pixely 5x5                  
 shapeToDraw = PIECES[piece['shape']][piece['rotation']]#PIECES[piece['shape']][piece['rotation']]            
 if pixelx == None and pixely == None: 
 #  ,'Next'            。      ,                  ,   drawPiece()      
# pixelx pixely      ,                      。
  pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])#            。
 for x in range(TEMPLATEWIDTH): #  5x5      
  for y in range(TEMPLATEHEIGHT):
   if shapeToDraw[y][x] != BLANK:
    drawBox(None, None, piece['color'], pixelx+(x * BOXSIZE), pixely + (y * BOXSIZE))
    #    ?               =                   +                  ,            

def drawNextPiece(piece):
 nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR)
 nextRect = nextSurf.get_rect()
 nextRect.topleft = (WINDOWWIDTH - 120, 80)
 DISPLAYSURF.blit(nextSurf, nextRect)
 drawPiece(piece, pixelx=WINDOWWIDTH-120, pixely=100)

def drawStatus(score, level):
 scoreSurf = BASICFONT.render('Score: %s' % score, True, TEXTCOLOR)
 scoreRect = scoreSurf.get_rect()
 scoreRect.topleft = (WINDOWWIDTH - 150, 20)
 DISPLAYSURF.blit(scoreSurf, scoreRect)
 levelSurf = BASICFONT.render('Level: %s' % level, True, TEXTCOLOR)
 levelRect = levelSurf.get_rect()
 levelRect.topleft = (WINDOWWIDTH - 150, 50)
 DISPLAYSURF.blit(levelSurf, levelRect)

def showTextScreen(text):
 titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTCOLOR)
 titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
 DISPLAYSURF.blit(titleSurf, titleRect)
 pressKeySurf, pressKeyRect = makeTextObjs('Press a key to play.', BASICFONT, TEXTCOLOR)
 pressKeyRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 100)
 DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
 while checkForKeyPress() == None:
  pygame.display.update()
  FPSCLOCK.tick()

if __name__ == '__main__':
 main()
这里写图片描述
这里写图片描述
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기