fork download
  1. # tetris.py
  2. # Mechanical MOOC MIT OCW 6.189
  3. # Glenn Richard
  4. # July 24, 2013
  5. # Modified July 28, 2013
  6. from graphics import *
  7. import random
  8.  
  9. ############################################################
  10. # BLOCK CLASS
  11. ############################################################
  12.  
  13. class Block(Rectangle):
  14. ''' Block class:
  15. Implement a block for a tetris piece
  16. Attributes: x - type: int
  17. y - type: int
  18. specify the position on the tetris board
  19. in terms of the square grid
  20. '''
  21.  
  22. BLOCK_SIZE = 30
  23. OUTLINE_WIDTH = 3
  24.  
  25. def __init__(self, pos, color):
  26. self.x = pos.x
  27. self.y = pos.y
  28.  
  29. p1 = Point(pos.x*Block.BLOCK_SIZE + Block.OUTLINE_WIDTH,
  30. pos.y*Block.BLOCK_SIZE + Block.OUTLINE_WIDTH)
  31. p2 = Point(p1.x + Block.BLOCK_SIZE, p1.y + Block.BLOCK_SIZE)
  32.  
  33. Rectangle.__init__(self, p1, p2)
  34. self.setWidth(Block.OUTLINE_WIDTH)
  35. self.setFill(color)
  36.  
  37. def can_move(self, board, dx, dy):
  38. ''' Parameters: dx - type: int
  39. dy - type: int
  40.  
  41. Return value: type: bool
  42.  
  43. checks if the block can move dx squares in the x direction
  44. and dy squares in the y direction
  45. Returns True if it can, and False otherwise
  46. HINT: use the can_move method on the Board object
  47. '''
  48. #YOUR CODE HERE
  49. return board.can_move(self.x + dx, self.y + dy)
  50.  
  51. def move(self, dx, dy):
  52. ''' Parameters: dx - type: int
  53. dy - type: int
  54.  
  55. moves the block dx squares in the x direction
  56. and dy squares in the y direction
  57. '''
  58.  
  59. self.x += dx
  60. self.y += dy
  61.  
  62. Rectangle.move(self, dx*Block.BLOCK_SIZE, dy*Block.BLOCK_SIZE)
  63.  
  64.  
  65.  
  66. ############################################################
  67. # SHAPE CLASS
  68. ############################################################
  69.  
  70. class Shape():
  71. ''' Shape class:
  72. Base class for all the tetris shapes
  73. Attributes: blocks - type: list - the list of blocks making up the shape
  74. rotation_dir - type: int - the current rotation direction of the shape
  75. shift_rotation_dir - type: Boolean - whether or not the shape rotates
  76. '''
  77.  
  78. def __init__(self, coords, color):
  79. self.blocks = []
  80. self.rotation_dir = 1
  81. ### A boolean to indicate if a shape shifts rotation direction or not.
  82. ### Defaults to false since only 3 shapes shift rotation directions (I, S and Z)
  83. self.shift_rotation_dir = False
  84.  
  85. for pos in coords:
  86. self.blocks.append(Block(pos, color))
  87.  
  88.  
  89.  
  90. def get_blocks(self):
  91. '''returns the list of blocks
  92. '''
  93. #YOUR CODE HERE
  94. return self.blocks
  95.  
  96. def draw(self, win):
  97. ''' Parameter: win - type: CanvasFrame
  98.  
  99. Draws the shape:
  100. i.e. draws each block
  101. '''
  102. for block in self.blocks:
  103. block.draw(win)
  104.  
  105. def move(self, dx, dy):
  106. ''' Parameters: dx - type: int
  107. dy - type: int
  108.  
  109. moves the shape dx squares in the x direction
  110. and dy squares in the y direction, i.e.
  111. moves each of the blocks
  112. '''
  113. for block in self.blocks:
  114. block.move(dx, dy)
  115.  
  116. def can_move(self, board, dx, dy):
  117. ''' Parameters: dx - type: int
  118. dy - type: int
  119.  
  120. Return value: type: bool
  121.  
  122. checks if the shape can move dx squares in the x direction
  123. and dy squares in the y direction, i.e.
  124. check if each of the blocks can move
  125. Returns True if all of them can, and False otherwise
  126.  
  127. '''
  128.  
  129. #YOUR CODE HERE
  130. # default implementation (MUST CHANGE)
  131. for block in self.blocks:
  132. if not block.can_move(board, dx,dy):
  133. return False
  134. return True
  135.  
  136. def get_rotation_dir(self):
  137. ''' Return value: type: int
  138.  
  139. returns the current rotation direction
  140. '''
  141. return self.rotation_dir
  142.  
  143. def can_rotate(self, board):
  144. ''' Parameters: board - type: Board object
  145. Return value: type : bool
  146.  
  147. Checks if the shape can be rotated.
  148.  
  149. 1. Get the rotation direction using the get_rotation_dir method
  150. 2. Compute the position of each block after rotation and check if
  151. the new position is valid
  152. 3. If any of the blocks cannot be moved to their new position,
  153. return False
  154.  
  155. otherwise all is good, return True
  156. '''
  157. #YOUR CODE HERE
  158. for block in self.blocks:
  159. x = self.blocks[1].x - self.rotation_dir * self.blocks[1].y + self.rotation_dir * block.y
  160. y = self.blocks[1].y + self.rotation_dir * self.blocks[1].x - self.rotation_dir * block.x
  161. dx = x - block.x
  162. dy = y - block.y
  163. if not block.can_move(board, dx, dy):
  164. return False
  165. return True
  166.  
  167. def rotate(self, board):
  168. ''' Parameters: board - type: Board object
  169.  
  170. rotates the shape:
  171. 1. Get the rotation direction using the get_rotation_dir method
  172. 2. Compute the position of each block after rotation
  173. 3. Move the block to the new position
  174.  
  175. '''
  176.  
  177. #### YOUR CODE HERE #####
  178. for block in self.blocks:
  179. x = self.blocks[1].x - self.rotation_dir * self.blocks[1].y + self.rotation_dir * block.y
  180. y = self.blocks[1].y + self.rotation_dir * self.blocks[1].x - self.rotation_dir * block.x
  181. block.move(x - block.x, y - block.y)
  182.  
  183.  
  184. ### This should be at the END of your rotate code.
  185. ### DO NOT touch it. Default behavior is that a piece will only shift
  186. ### rotation direction after a successful rotation. This ensures that
  187. ### pieces which switch rotations definitely remain within their
  188. ### accepted rotation positions.
  189. if self.shift_rotation_dir:
  190. self.rotation_dir *= -1
  191.  
  192.  
  193.  
  194. ############################################################
  195. # ALL SHAPE CLASSES
  196. ############################################################
  197.  
  198.  
  199. class I_shape(Shape):
  200. def __init__(self, center):
  201. coords = [Point(center.x - 2, center.y),
  202. Point(center.x - 1, center.y),
  203. Point(center.x , center.y),
  204. Point(center.x + 1, center.y)]
  205. Shape.__init__(self, coords, 'blue')
  206. self.shift_rotation_dir = True
  207. self.center_block = self.blocks[2]
  208.  
  209. class J_shape(Shape):
  210. def __init__(self, center):
  211. coords = [Point(center.x - 1, center.y),
  212. Point(center.x , center.y),
  213. Point(center.x + 1, center.y),
  214. Point(center.x + 1, center.y + 1)]
  215. Shape.__init__(self, coords, 'orange')
  216. self.center_block = self.blocks[1]
  217.  
  218. class L_shape(Shape):
  219. def __init__(self, center):
  220. coords = [Point(center.x - 1, center.y),
  221. Point(center.x , center.y),
  222. Point(center.x + 1, center.y),
  223. Point(center.x - 1, center.y + 1)]
  224. Shape.__init__(self, coords, 'cyan')
  225. self.center_block = self.blocks[1]
  226.  
  227.  
  228. class O_shape(Shape):
  229. def __init__(self, center):
  230. coords = [Point(center.x , center.y),
  231. Point(center.x - 1, center.y),
  232. Point(center.x , center.y + 1),
  233. Point(center.x - 1, center.y + 1)]
  234. Shape.__init__(self, coords, 'red')
  235. self.center_block = self.blocks[0]
  236.  
  237. def rotate(self, board):
  238. # Override Shape's rotate method since O_Shape does not rotate
  239. return
  240.  
  241. class S_shape(Shape):
  242. def __init__(self, center):
  243. coords = [Point(center.x , center.y),
  244. Point(center.x , center.y + 1),
  245. Point(center.x + 1, center.y),
  246. Point(center.x - 1, center.y + 1)]
  247. Shape.__init__(self, coords, 'green')
  248. self.center_block = self.blocks[0]
  249. self.shift_rotation_dir = True
  250. self.rotation_dir = -1
  251.  
  252.  
  253. class T_shape(Shape):
  254. def __init__(self, center):
  255. coords = [Point(center.x - 1, center.y),
  256. Point(center.x , center.y),
  257. Point(center.x + 1, center.y),
  258. Point(center.x , center.y + 1)]
  259. Shape.__init__(self, coords, 'yellow')
  260. self.center_block = self.blocks[1]
  261.  
  262.  
  263. class Z_shape(Shape):
  264. def __init__(self, center):
  265. coords = [Point(center.x - 1, center.y),
  266. Point(center.x , center.y),
  267. Point(center.x , center.y + 1),
  268. Point(center.x + 1, center.y + 1)]
  269. Shape.__init__(self, coords, 'magenta')
  270. self.center_block = self.blocks[1]
  271. self.shift_rotation_dir = True
  272. self.rotation_dir = -1
  273.  
  274.  
  275.  
  276. ############################################################
  277. # BOARD CLASS
  278. ############################################################
  279.  
  280. class Board():
  281. ''' Board class: it represents the Tetris board
  282.  
  283. Attributes: width - type:int - width of the board in squares
  284. height - type:int - height of the board in squares
  285. canvas - type:CanvasFrame - where the pieces will be drawn
  286. grid - type:Dictionary - keeps track of the current state of
  287. the board; stores the blocks for a given position
  288. '''
  289.  
  290. def __init__(self, win, width, height):
  291. self.width = width
  292. self.height = height
  293.  
  294. # create a canvas to draw the tetris shapes on
  295. self.canvas = CanvasFrame(win, self.width * Block.BLOCK_SIZE,
  296. self.height * Block.BLOCK_SIZE)
  297. self.canvas.setBackground('light gray')
  298.  
  299. # create an empty dictionary
  300. # currently we have no shapes on the board
  301. self.grid = {}
  302.  
  303. def draw_shape(self, shape):
  304. ''' Parameters: shape - type: Shape
  305. Return value: type: bool
  306.  
  307. draws the shape on the board if there is space for it
  308. and returns True, otherwise it returns False
  309. '''
  310. if shape.can_move(self, 0, 0):
  311. shape.draw(self.canvas)
  312. return True
  313. return False
  314.  
  315. def can_move(self, x, y):
  316. ''' Parameters: x - type:int
  317. y - type:int
  318. Return value: type: bool
  319.  
  320. 1. check if it is ok to move to square x,y
  321. if the position is outside of the board boundaries, can't move there
  322. return False
  323.  
  324. 2. if there is already a block at that postion, can't move there
  325. return False
  326.  
  327. 3. otherwise return True
  328.  
  329. '''
  330.  
  331. #YOUR CODE HERE
  332. if not (0 <= x < self.width and 0 <= y < self.height):
  333. return False
  334. if (x, y) in self.grid:
  335. return False
  336. return True
  337.  
  338. def add_shape(self, shape):
  339. ''' Parameter: shape - type:Shape
  340.  
  341. add a shape to the grid, i.e.
  342. add each block to the grid using its
  343. (x, y) coordinates as a dictionary key
  344.  
  345. Hint: use the get_blocks method on Shape to
  346. get the list of blocks
  347.  
  348. '''
  349.  
  350. #YOUR CODE HERE
  351. for block in shape.get_blocks():
  352. self.grid[block.x, block.y] = block
  353.  
  354.  
  355. def delete_row(self, y):
  356. ''' Parameters: y - type:int
  357.  
  358. remove all the blocks in row y
  359. to remove a block you must remove it from the grid
  360. and erase it from the screen.
  361. If you dont remember how to erase a graphics object
  362. from the screen, take a look at the Graphics Library
  363. handout
  364.  
  365. '''
  366.  
  367. #YOUR CODE HERE
  368. for x in range(self.width):
  369. self.grid[x, y].undraw()
  370. del self.grid[x, y]
  371.  
  372. def is_row_complete(self, y):
  373. ''' Parameter: y - type: int
  374. Return value: type: bool
  375.  
  376. for each block in row y
  377. check if there is a block in the grid (use the in operator)
  378. if there is one square that is not occupied, return False
  379. otherwise return True
  380.  
  381. '''
  382.  
  383. #YOUR CODE HERE
  384. for x in range(self.width):
  385. if not (x, y) in self.grid:
  386. return False
  387. return True
  388.  
  389. def move_down_rows(self, y_start):
  390. ''' Parameters: y_start - type:int
  391.  
  392. for each row from y_start to the top
  393. for each column
  394. check if there is a block in the grid
  395. if there is, remove it from the grid
  396. and move the block object down on the screen
  397. and then place it back in the grid in the new position
  398.  
  399. '''
  400.  
  401. #YOUR CODE HERE
  402. for y in range(y_start, -1, -1):
  403. for x in range(self.width):
  404. if (x, y) in self.grid:
  405. block = self.grid[x, y]
  406. block.undraw()
  407. del self.grid[x, y]
  408. block.move(0, 1)
  409. self.grid[block.x, block.y] = block
  410. block.draw(self.canvas)
  411. # TO BE COMPLETED - Remember that if an I-shape in vertical
  412. # position can no longer move, non-contiguous rows
  413. # may have become completed
  414.  
  415. def remove_complete_rows(self):
  416. # This one controls the process; calls the other methods as helpers
  417. ''' removes all the complete rows
  418. 1. for each row, y,
  419. 2. check if the row is complete
  420. if it is,
  421. delete the row
  422. move all rows down starting at row y - 1
  423.  
  424. '''
  425.  
  426. #YOUR CODE HERE
  427. for y in range(self.height):
  428. if self.is_row_complete(y):
  429. self.delete_row(y)
  430. self.move_down_rows(y - 1)
  431.  
  432. def game_over(self):
  433. ''' display "Game Over !!!" message in the center of the board
  434. HINT: use the Text class from the graphics library
  435. '''
  436.  
  437. #YOUR CODE HERE
  438. game_over_message = Text(Point(150, 100), "Game over")
  439. game_over_message.setSize(32)
  440. game_over_message.setTextColor("black")
  441. game_over_message.draw(self.canvas)
  442.  
  443.  
  444. ############################################################
  445. # TETRIS CLASS
  446. ############################################################
  447.  
  448. class Tetris():
  449. ''' Tetris class: Controls the game play
  450. Attributes:
  451. SHAPES - type: list (list of Shape classes)
  452. DIRECTION - type: dictionary - converts string direction to (dx, dy)
  453. BOARD_WIDTH - type:int - the width of the board
  454. BOARD_HEIGHT - type:int - the height of the board
  455. board - type:Board - the tetris board
  456. win - type:Window - the window for the tetris game
  457. delay - type:int - the speed in milliseconds for moving the shapes
  458. current_shape - type: Shape - the current moving shape on the board
  459. '''
  460.  
  461. SHAPES = [I_shape, J_shape, L_shape, O_shape, S_shape, T_shape, Z_shape]
  462. DIRECTION = {'Left':(-1, 0), 'Right':(1, 0), 'Down':(0, 1)}
  463. BOARD_WIDTH = 10
  464. BOARD_HEIGHT = 20
  465.  
  466. def __init__(self, win):
  467. self.board = Board(win, self.BOARD_WIDTH, self.BOARD_HEIGHT)
  468. self.win = win
  469. self.delay = 1000 #ms
  470.  
  471. # sets up the keyboard events
  472. # when a key is called the method key_pressed will be called
  473. self.win.bind_all('<Key>', self.key_pressed)
  474.  
  475. # set the current shape to a random new shape
  476. self.current_shape = self.create_new_shape()
  477.  
  478. # Draw the current_shape on the board (take a look at the
  479. # draw_shape method in the Board class)
  480. #### YOUR CODE HERE ####
  481. self.board.draw_shape(self.current_shape)
  482. # For Step 9: animate the shape!
  483. #### YOUR CODE HERE ####
  484. self.animate_shape()
  485.  
  486. def create_new_shape(self):
  487. ''' Return value: type: Shape
  488.  
  489. Create a random new shape that is centered
  490. at y = 0 and x = int(self.BOARD_WIDTH/2)
  491. return the shape
  492. '''
  493.  
  494. #YOUR CODE HERE
  495. return Tetris.SHAPES[random.randint(0, len(Tetris.SHAPES) - 1)] (Point(int(self.BOARD_WIDTH/2), 0))
  496.  
  497. def animate_shape(self):
  498. ''' animate the shape - move down at equal intervals
  499. specified by the delay attribute
  500. '''
  501.  
  502. self.do_move('Down')
  503. self.win.after(self.delay, self.animate_shape)
  504.  
  505. def do_move(self, direction):
  506. ''' Parameters: direction - type: string
  507. Return value: type: bool
  508.  
  509. Move the current shape in the direction specified by the parameter:
  510. First check if the shape can move. If it can, move it and return True
  511. Otherwise if the direction we tried to move was 'Down',
  512. 1. add the current shape to the board
  513. 2. remove the completed rows if any
  514. 3. create a new random shape and set current_shape attribute
  515. 4. If the shape cannot be drawn on the board, display a
  516. game over message
  517.  
  518. return False
  519.  
  520. '''
  521. # print direction
  522.  
  523. #YOUR CODE HERE
  524. dx, dy = self.DIRECTION[direction]
  525. if self.current_shape.can_move(self.board, dx, dy):
  526. self.current_shape.move(dx, dy)
  527. return True
  528. else:
  529. if direction == "Down":
  530. self.board.add_shape(self.current_shape)
  531. self.board.remove_complete_rows()
  532. self.current_shape = self.create_new_shape()
  533. if not self.board.draw_shape(self.current_shape):
  534. self.board.game_over()
  535. return False
  536.  
  537. def do_rotate(self):
  538. ''' Checks if the current_shape can be rotated and
  539. rotates if it can
  540. '''
  541.  
  542. #YOUR CODE HERE
  543. if self.current_shape.can_rotate(self.board):
  544. self.current_shape.rotate(self.board)
  545. return True
  546. return False
  547.  
  548. def key_pressed(self, event):
  549. ''' this function is called when a key is pressed on the keyboard
  550. it currenly just prints the value of the key
  551.  
  552. Modify the function so that if the user presses the arrow keys
  553. 'Left', 'Right' or 'Down', the current_shape will move in
  554. the appropriate direction
  555.  
  556. if the user presses the space bar 'space', the shape will move
  557. down until it can no longer move and is added to the board
  558.  
  559. if the user presses the 'Up' arrow key ,
  560. the shape should rotate.
  561.  
  562. '''
  563.  
  564. #YOUR CODE HERE
  565. key = event.keysym
  566. if key in self.DIRECTION:
  567. self.do_move(key)
  568. elif key == "Up":
  569. self.do_rotate()
  570. elif key == "space":
  571. while self.do_move("Down") == True:
  572. pass
  573. # print key
  574.  
  575. ################################################################
  576. # Start the game
  577. ################################################################
  578.  
  579. win = Window("Tetris")
  580. game = Tetris(win)
  581. win.mainloop()
  582.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout

Standard output is empty