Guest User

Untitled

a guest
May 7th, 2017
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.82 KB | None | 0 0
  1. import random,time,pygame,sys
  2. from pygame.locals import *
  3. FPS=25
  4. WINDOWWIDTH=640
  5. WINDOWHEIGHT=480
  6. BOXSIZE=20
  7. BOARDWIDTH=10
  8. BOARDHEIGHT=20
  9. BLANK="."
  10. MOVESIDEWAYSFREQ= 0.15
  11. MOVEDOWNFREQ= 0.01
  12. XMARGIN=int((WINDOWWIDTH-BOARDWIDTH*BOXSIZE)/2)
  13. TOPMARGIN=WINDOWHEIGHT-(BOARDHEIGHT*BOXSIZE) -5
  14. WHITE = (255, 255, 255)
  15. GRAY = (185, 185, 185)
  16. BLACK = ( 0, 0, 0)
  17. RED = (155, 0, 0)
  18. LIGHTRED = (175, 20, 20)
  19. GREEN = ( 0, 155, 0)
  20. LIGHTGREEN = ( 20, 175, 20)
  21. BLUE = ( 0, 0, 155)
  22. LIGHTBLUE = ( 20, 20, 175)
  23. YELLOW = (155, 155, 0)
  24. LIGHTYELLOW = (175, 175, 20)
  25.  
  26. BORDERCOLOR = BLUE
  27. BGCOLOR = BLACK
  28. TEXTCOLOR = WHITE
  29. TEXTSHADOWCOLOR = GRAY
  30. COLORS = ( BLUE, GREEN, RED, YELLOW)
  31. LIGHTCOLORS = (LIGHTBLUE, LIGHTGREEN, LIGHTRED, LIGHTYELLOW)
  32. assert len(COLORS) == len(LIGHTCOLORS) #each color must have light color
  33.  
  34. TEMPLATEWIDTH = 5
  35. TEMPLATEHEIGHT = 5
  36. S_SHAPE_TEMPLATE = [['.....',
  37. '.....',
  38. '..OO.',
  39. '.OO..',
  40. '.....'],
  41. ['.....',
  42. '..O..',
  43. '..OO.',
  44. '...O.',
  45. '.....']]
  46.  
  47. Z_SHAPE_TEMPLATE = [['.....',
  48. '.....',
  49. '.OO..',
  50. '..OO.',
  51. '.....'],
  52. ['.....',
  53. '..O..',
  54. '.OO..',
  55. '.O...',
  56. '.....']]
  57.  
  58. I_SHAPE_TEMPLATE = [['..O..',
  59. '..O..',
  60. '..O..',
  61. '..O..',
  62. '.....'],
  63. ['.....',
  64. '.....',
  65. 'OOOO.',
  66. '.....',
  67. '.....']]
  68.  
  69. O_SHAPE_TEMPLATE = [['.....',
  70. '.....',
  71. '.OO..',
  72. '.OO..',
  73. '.....']]
  74.  
  75. J_SHAPE_TEMPLATE = [['.....',
  76. '.O...',
  77. '.OOO.',
  78. '.....',
  79. '.....'],
  80. ['.....',
  81. '..OO.',
  82. '..O..',
  83. '..O..',
  84. '.....'],
  85. ['.....',
  86. '.....',
  87. '.OOO.',
  88. '...O.',
  89. '.....'],
  90. ['.....',
  91. '..O..',
  92. '..O..',
  93. '.OO..',
  94. '.....']]
  95.  
  96. L_SHAPE_TEMPLATE = [['.....',
  97. '...O.',
  98. '.OOO.',
  99. '.....',
  100. '.....'],
  101. ['.....',
  102. '..O..',
  103. '..O..',
  104. '..OO.',
  105. '.....'],
  106. ['.....',
  107. '.....',
  108. '.OOO.',
  109. '.O...',
  110. '.....'],
  111. ['.....',
  112. '.OO..',
  113. '..O..',
  114. '..O..',
  115. '.....']]
  116.  
  117. T_SHAPE_TEMPLATE = [['.....',
  118. '..O..',
  119. '.OOO.',
  120. '.....',
  121. '.....'],
  122. ['.....',
  123. '..O..',
  124. '..OO.',
  125. '..O..',
  126. '.....'],
  127. ['.....',
  128. '.....',
  129. '.OOO.',
  130. '..O..',
  131. '.....'],
  132. ['.....',
  133. '..O..',
  134. '.OO..',
  135. '..O..',
  136. '.....']]
  137.  
  138. PIECES = {'S': S_SHAPE_TEMPLATE,
  139. 'Z': Z_SHAPE_TEMPLATE,
  140. 'J': J_SHAPE_TEMPLATE,
  141. 'L': L_SHAPE_TEMPLATE,
  142. 'I': I_SHAPE_TEMPLATE,
  143. 'O': O_SHAPE_TEMPLATE,
  144. 'T': T_SHAPE_TEMPLATE}
  145.  
  146. def main():
  147. global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT
  148. pygame.init()
  149. FPSCLOCK = pygame.time.Clock()
  150. DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
  151. BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  152. BIGFONT = pygame.font.Font('freesansbold.ttf',100)
  153. pygame.display.set_caption('Hannah')
  154.  
  155. showTextScreen('Hannah')
  156. while True:
  157. #if random.randint(0, 1) ==0:
  158. #continue
  159. #pygame.mixer.music.load('tetrisb.mid')
  160. #else:
  161. #pygame.mixer.music.load('tetrisc.mid')
  162. #pygame.mixer.music.play(-1,0.0)
  163. #pygame.mixer.music.stop()
  164. runGame()
  165. showTextScreen('Game Over')
  166.  
  167. def runGame():
  168. # setup variables for the star of the game
  169. board = getBlankBoard()
  170. lastMoveDownTime = time.time()
  171. lastMoveSidewaysTime = time.time()
  172. lastFallTime = time.time()
  173. movingDown = False # note : there is no movingUp variable
  174. movingLeft = False
  175. movingRight = False
  176. score = 0
  177. level, fallFreq =calculateLevelAndFallFreq (score)
  178.  
  179. fallingPiece = getNewPiece ()
  180. nextPiece = getNewPiece()
  181.  
  182. while True: #game loop
  183. if fallingPiece == None:
  184. #no falling piece in play, so start new piece at top
  185. fallingPiece = nextPiece
  186. nextPiece = getNewPiece()
  187. lastFallTime = time.time() # reset lastFallTime
  188.  
  189. if not isValidPosition(board, fallingPiece) :
  190. return # can't fit a new piece on the board, so game over
  191.  
  192. checkForQuit()
  193. for event in pygame.event.get(): # event handling loop
  194. if event.type == KEYUP:
  195. if (event.key ==K_p):
  196. # pausing game
  197. DISPLAYSURF.fill(BGCOLOR)
  198. pygame.mixer.music.stop()
  199. showTextScreen('Paused')
  200. # pause until a key press
  201. pygame.mixer.music.play(-1,0,0)
  202. lastFallTime = time.time()
  203. lastMoveDownTime = time.time()
  204. lastMovesSidewaysTime = time.time()
  205. elif (event.key == K_LEFT or event.key ==K_a):
  206. movingLeft = False
  207. elif (event.key == K_RIGHT or event.key ==K_d):
  208. movingLeft = False
  209. elif (event.key == K_DOWN or event.key ==K_s):
  210. movingLeft = False
  211.  
  212. elif event.type == KEYDOWN:
  213. # moving the piece sideways
  214. if (event.key ==K_LEFT or event.key ==K_a) and isValidPosition (board, fallingPiece, adjX=-1):
  215. fallingPiece['x'] += 1
  216. movingLeft = True
  217. movingRight = False
  218. lastMovesSidewaysTime = time.time()
  219.  
  220. elif (event.key ==K_RIGHT or event.key ==K_d) and isValidPosition (board, fallingPiece, adjX=1):
  221. fallingPiece['x'] += 1
  222. movingRight = True
  223. movingLeft = False
  224. lastMovesSidewaysTime = time.time()
  225. # rotating the piece (if there is room to rotate)
  226. elif (event.key == K_UP or event.key == K_w):
  227. fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
  228. if not isValidPosition(board, fallingPiece):
  229. fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
  230. elif (event.key == K_q): # rotate the other direction
  231. fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
  232. if not isValidPosition(board, fallingPiece):
  233. fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
  234.  
  235. # making the piece fall faster with the down key
  236. elif(event.key ==K_DOWN or event.key==K_s):
  237. movingDown = true
  238. if isValidPostition(board, fallingPiece, adjY=1):
  239. fallingPiece['y'] += 1
  240. lastMoveDownTime = time.time()
  241.  
  242. #move the current piece all the way down
  243. elif event.key == K_SPACE:
  244. movingDown = False
  245. movingLeft = False
  246. movingRight = False
  247. for i in range (1, BOARDHEIGHT):
  248. if not isValidPosition(board, fallingPiece, adjY=i):
  249. break
  250. fallingPiece['y'] += i - 1
  251.  
  252. # handle moving the piece because of user input
  253. if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:
  254. if movingLeft and isValidPosition(board, fallingPiece, adjX=-1):
  255. fallingPiece['x'] -= 1
  256. elif movingRight and isValidPosition(board, fallingPiece, adjX=1):
  257. fallingPiece['x'] += 1
  258. lastMoveSidewaysTime = time.time()
  259.  
  260. if movingDown and time.time() - lastMoveDownTime > MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1):
  261. fallingPiece['y'] += 1
  262. lastMoveDownTime = time.time()
  263.  
  264. # let the piece fall if it is time to fall
  265. if time.time() - lastFallTime > fallFreq:
  266. # see if the piece has landed
  267. if not isValidPosition(board, fallingPiece, adjY=1):
  268. # falling piece has landed, set it on the board
  269. addToBoard(board, fallingPiece)
  270. score += removeCompleteLines(board)
  271. level, fallFreq = calculateLevelAndFallFreq(score)
  272. fallingPiece = None
  273. else:
  274. # piece did not land, just move the piece down
  275. fallingPiece['y'] += 1
  276. lastFallTime = time.time()
  277.  
  278. # Drawing everything on the screen
  279. DISPLAYSURF.fill(BGCOLOR)
  280. drawBoard(board)
  281. drawStatus(score, level)
  282. drawNectPiece (nextPiece)
  283. if fallingPiece != None:
  284. drawPiece(fallingPiece)
  285.  
  286. pygame.display.update()
  287. FPSCLOCK.tick(FPS)
  288.  
  289. def makeTextObjs (text, font, color):
  290. surf = font.render(text, True, color)
  291. return surf, surf.get_rect()
  292.  
  293. def terminate( ):
  294. pygame.quit( )
  295. sys.exit( )
  296.  
  297.  
  298. def checkForKeyPress():
  299. # go through event queue looking for a keyup event
  300. # grab keydown events to remove them from the event queue
  301.  
  302. for event in pygame.event.get([KEYDOWN, KEYUP]):
  303. if event.type == KEYDOWN:
  304. continue
  305. return event.key
  306. return None
  307.  
  308. def showTextScreen (text):
  309. # this function displays large text in the center of the screen
  310. # until a key is pressed
  311. # Draw the text drop shadow
  312. titleSurf,titleRect = makeTextObjs(text, BIGFONT, TEXTSHADOWCOLOR)
  313. titleRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2))
  314. DISPLAYSURF.blit(titleSurf, titleRect)
  315.  
  316. # Draw the additional " press a key to play." text.
  317. pressKeySurf, pressKeyRect = makeTextObjs('Press a key to play.', BASICFONT, TEXTCOLOR)
  318. pressKeyRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 100)
  319. DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
  320.  
  321. while checkForKeyPress() == None:
  322. pygame.display.update()
  323. FPSCLOCK.tick()
  324.  
  325. def checkForQuit():
  326. for event in pygame.event.get(QUIT): # get all the quit events
  327. terminate() # terminate if any quit events are present
  328. for event in pygame.event.get(KEYUP): #get all the keyup events
  329. if event.key == K_ESCAPE:
  330. terminate() # terminate if the keyup event was for the esc key
  331. pygame.event.post(Event) # put the other keyup event objects back
  332.  
  333. def calculateLevelAndFallFreq (score):
  334. # based on the score returnt the level the player is on and how many seconds pass until a falling piece falls one space.
  335. level = int(score / 10) + 1
  336. fallFreq = 0.27 - (level * .02)
  337. return level, fallFreq
  338.  
  339. def getNewPiece():
  340. # return a random new piece in a random rotation and color
  341. shape = random.choice(list(PIECES.keys()))
  342. newPiece = {'shape': shape,
  343. 'rotation': random.randint(0, len(PIECES[shape]) - 1),
  344. 'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2),
  345. 'y': -2, # start it above the board (i.e. less than 0)
  346. 'color': random.randint(0, len(COLORS)-1)}
  347.  
  348. return newPiece
  349.  
  350. def addToBoard(board, piece):
  351. # fill in the board based onn piece's location, shape, and rotation
  352. for x in range(TEMPLATEWIDTH):
  353. for y in rand(TEMPLATEHEIGHT):
  354. if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:
  355. board[x + piece['x']][y+ piece['y']] = [piece['color']]
  356.  
  357. def getBlankBoard():
  358. # create and return a new blank board data structure
  359. board = []
  360. for i in range(BOARDWIDTH):
  361. board.append([BLANK] * BOARDHEIGHT)
  362. return board
  363.  
  364. def isOnBoard(x,y):
  365. return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT
  366. def isValidPosition(board, piece, adjX=0, adjY=0):
  367. for x in range(TEMPLATEWIDTH):
  368. for y in range (TEMPLATEHEIGHT):
  369. isAboveBoard = y+piece ['y']+ adjY <0
  370. if AboveBoard or PIECES[piece['shape']][piece['rotation']][x][y] ==BLANK:
  371. continue
  372. if not isOnBoard (x+piece['x'], + adjX, y+piece ['y']+ adjY):
  373. return False
  374. if board[x+piece['x'], + adjX][y+piece ['y']+ adjY]!= BLANK:
  375. return False
  376. return True
  377.  
  378. def isCompleteLine(board, y):
  379. for x in range (BOARDWIDTH):
  380. if board[x][y] == BLANK:
  381. return False
  382. return True
  383. def removeCompleteLines(board):
  384. numLinesRemoved = 0
  385. y=BOARDHEIGHT -1
  386. while y>= 0:
  387. if isCompleteLine (board,y):
  388. for pullDownY in range (y, 0, -1):
  389. for x in range(BOARDWIDTH):
  390. board[x][pullDownY]=board[x][pullDownY-1]
  391. for x in range(BOARDWIDTH):
  392. board[x][0]= BLANK
  393. numLinesRemoved+=1
  394. else:
  395. y-=1
  396.  
  397. return numLinesRemoved
  398.  
  399. def convertToPixelCoords(boxx, boxy):
  400. return (XMARGIN+(boxx*BOXSIZE)), (TOPMARGIN+(boxy*BOXSIZE))
  401.  
  402. def drawBox (boxx,boxy,color,pixelx=None,pixely=None):
  403. if color==BLANK:
  404. return
  405. if pixelx==None and pixely==None:
  406. pixelx,pixely=convertToPixelCoords(boxx,boxy)
  407. pygame.draw.rect(DISPLAYSURF, COLORS[color],(pixelx+1, pixely+1, BOXSIZE-1,BOXSIZE-1))
  408. pygame.draw.rect(DISPLAYSURF, LIGHTCOLORS[color],(pixelx+1, pixely+1, BOXSIZE-4,BOXSIZE-4))
  409.  
  410. def drawBoard(board):
  411. #draw border around board
  412. pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN - 3, TOPMARGIN - 7, (BOARDWIDTH * BOXSIZE) + 8, (BOARDHEIGHT * BOXSIZE) + 8), 5)
  413.  
  414. #fill background of board
  415. pygame.draw.rect(DISPLAYSURF, BGCOLOR, (XMARGIN, TOPMARGIN, BOXSIZE * BOARDWIDTH, BOXSIZE * BOARDHEIGHT))
  416. #draw individual boxes on board
  417. for x in range(BOARDWIDTH):
  418. for y in range(BOARDHEIGHT):
  419. drawBox(x, y, board[x][y])
  420.  
  421. def drawStatus(score, level):
  422. scoreSurf = BASICFONT.render('Score: %s' % score, True, TEXTCOLOR)
  423. scoreRect = scoreSurf.get_rect()
  424. scoreRect.topleft = (WINDOWWIDTH-150, 20)
  425. DISLAYSURF.blit(scoreSurf, scoreRect)
  426.  
  427. levelSurf = BASICFONT.render('Level: %s' % level, True, TEXTCOLOR)
  428. levelRect = levelSurf.get_rect()
  429. levelRect.topleft = (WINDOWWIDTH-150, 20)
  430. DISLAYSURF.blit(levelSurf, levelRect)
  431.  
  432. def drawPiece (piece, pixelx=None, pixely=None):
  433. shapeTodraw = PIECES[piece['shape']][piece['rotation']]
  434. if pixelx == None and pixely == None:
  435. pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])
  436. for x in range (TEMPLATEWIDTH):
  437. for y in range (TEMPLATEHEIGHT):
  438. if shapeToDraw[y][x] != BLANK:
  439. drawBox (None, piece['color'], pixelx+(x*BOXSIZE), pixely+(y*BOXSIZE))
  440. def drawNextPiece(piece):
  441. nextSurf=BASICFONT.render('Next:', True, TEXTCOLOR)
  442. nextRect=nextSurf.get_rect()
  443. nextRect.topleft=(WINDOWWIDTH-120,80)
  444. DISPLAY.blit(nextSurf, nextRect)
  445. drawPiece(piece, pixelx=WINDOWWIDTH-120, pixely=100)
  446.  
  447. if __name__== '__main__':
  448. main()
Advertisement
Add Comment
Please, Sign In to add comment