GAME of TETRIS
My design includes two main elements: a board and a falling piece. Falling piece is not part of the board, but is drawn over the board. The board is a 2 dimensional list of colors.Initially the board is full of one color (empty color), As falling piece transfered onto the board, the other colors are introduced.The goal of the game is to fill rows entirely with non-empty colors. For complete guidance you can refer to the address in bellow:
Important parts in coding for this play are brought here:
There are 6 basic functions for animations in python, "mousePressed(canvas, event)" , "keyPressed(canvas, event)" , "timerFired(canvas)" , " redraw (canvas)", "init(canvas)" and "run()".
So I show how these functions work in my coding.
By paying attention to the other main functions, name
"moving falling piece", "falling piece is legal", " rotate falling piece ", " place falling piece ", " draw game/ board/ score/ cell ", " new falling piece ", " draw falling piece" " make piece"; in my coding you can completely understand how this game is designed.
PROGRAMMING by PYTHON
These examples are done in
"15 112/ Fundamental of Programming and Computer Science" Course,
Special Thanks to Professor David Kosbie
Spring 2013
GAME of SNAKE
about play, by eating green circle as the food the length of the snake increse one unit. And as the red circle is a poison, if the snake eat it, it will die. In the second picture that is in the debugging mood you can see how the process of adding numbers to the length of snake or decresing the numbers by moving in empty places showing by zero happened.
again in this game, the 6 parts of animation coding in my way of coding is shown. for the other eccential parts of coding, pay attention to the complete python file.
import randomfrom Tkinter import *
# if mouse is pressed and it is paused put a wall or remove the existing wall
def mousePressed(canvas,event):
if (canvas.data.ispaused): #checks if the game is paused
(y,x)=(event.x, event.y)
cellSize=canvas.data.cellSize
margin = canvas.data.margin
row = ((x - margin - 2 * cellSize) / cellSize)
col = ((y - margin) / cellSize)
if (row>=0 and col>=0):
snakeBoard = canvas.data.snakeBoard
if (snakeBoard[row][col]==-3):
snakeBoard[row][col]=0
#checks if there is any wall remained after removing clicked one
checkWall(canvas)
if (snakeBoard[row][col]==0):
snakeBoard[row][col]=-3
canvas.data.isThereWall=True # shows we have at least one wall
redrawAll(canvas)
# checks if there is any wall remained on the board
def checkWall(canvas):
board=canvas.data.snakeBoard
for row in range(canvas.data.rows):
for col in range (canvas.data.cols):
if board[row][col]==-3:
canvas.data.isThereWall=True
return True
canvas.data.isThereWall=False
return False
def keyPressed(canvas,event):
canvas.data.ignoreNextTimerEvent = True # for better timing
# first process keys that work even if the game is over
if (event.char == "q"): gameOver(canvas) # q quits the game
elif (event.char == "r"): init(canvas) # r resets the game
elif (event.char == "d"): # shows the debug mode
canvas.data.inDebugMode = not canvas.data.inDebugMode
elif (event.char == "p"): # p pauses and unpauses the game
canvas.data.ispaused = not canvas.data.ispaused
# now process keys that only work if the game is not over
if (canvas.data.isGameOver == False and canvas.data.ispaused == False):
if (event.keysym == "Up"):
moveSnake(canvas,-1, 0) #turn the snake to the up
elif (event.keysym == "Down"):
moveSnake(canvas,+1, 0) #turn the snake to the down
elif (event.keysym == "Left"):
moveSnake(canvas,0,-1) #turn the snake to the left
elif (event.keysym == "Right"):
moveSnake(canvas,0,+1) #turn the snake to the right
redrawAll(canvas)
# move the snake one step forward in the given direction.
def moveSnake(canvas,drow, dcol):
(canvas.data.snakeDrow, canvas.data.snakeDcol) = (drow,dcol)
snakeBoard = canvas.data.snakeBoard
rows,cols = len(snakeBoard),len(snakeBoard[0])
headRow,headCol = canvas.data.headRow,canvas.data.headCol
newHeadRow,newHeadCol = headRow + drow, headCol + dcol
if ((newHeadRow<0)or(newHeadRow>=rows)or(newHeadCol<0)or(newHeadCol>=cols)):
gameOver(canvas)
elif (snakeBoard[newHeadRow][newHeadCol] > 0): # snake ran into itself!
gameOver(canvas)
elif (snakeBoard[newHeadRow][newHeadCol] == -1): # eating food! Yum!
snakeBoard[newHeadRow][newHeadCol] = 1 + snakeBoard[headRow][headCol];
canvas.data.headRow,canvas.data.headCol = newHeadRow, newHeadCol
canvas.data.score = canvas.data.score + 1
placeFood(canvas)
elif (snakeBoard[newHeadRow][newHeadCol] == -2): # eating poison!
gameOver(canvas)
elif (snakeBoard[newHeadRow][newHeadCol] == -3): # hitting to the wall
snakeBoard[newHeadRow][newHeadCol] = 0
canvas.data.score = canvas.data.score - 1 #reduce one from score
if canvas.data.score<0: # if score was zero and hit to a wall gameisover
gameOver(canvas)
else: # normal move forward (not eating food)
snakeBoard[newHeadRow][newHeadCol] = 1 + snakeBoard[headRow][headCol];
canvas.data.headRow, canvas.data.headCol = newHeadRow, newHeadCol
removeTail(canvas)
# find every snake cell and subtract 1 from it. When we're done,
# the old tail (which was 1) will become 0, so will not be part of the snake
# So the snake shrinks by 1 value, the tail.
def removeTail(canvas):
snakeBoard = canvas.data.snakeBoard
rows = len(snakeBoard)
cols = len(snakeBoard[0])
for row in range(rows):
for col in range(cols):
if (snakeBoard[row][col] > 0):
snakeBoard[row][col] -= 1 #reduce one from each cell of snake
# if the game is over add the score to score baord and sort it if it is more
# than three remove the rest and show the top three
def gameOver(canvas):
canvas.data.isGameOver = True
score = canvas.data.score
highScores = canvas.data.highScores
highScores.append(score)
highScores.sort() #sort them in ascending order
highScores.reverse() #reverse the order to decending order
if (len(highScores)>3):
highScores = highScores[0:3] #cuts the top three
canvas.data.highScores = highScores
# moves the snake forward with the assigned speed
# keeps counting so if the wall is in the game increase the score in each level
def timerFired(canvas):
ignoreThisTimerEvent = canvas.data.ignoreNextTimerEvent
canvas.data.ignoreNextTimerEvent = False
if ((canvas.data.isGameOver == False) and
(ignoreThisTimerEvent == False) and (canvas.data.ispaused == False)):
# only process timerFired if game is not over or paused
drow,dcol = canvas.data.snakeDrow, canvas.data.snakeDcol
moveSnake(canvas,drow, dcol)
if canvas.data.isThereWall: canvas.data.counter += 1
if canvas.data.counter == 20: # if counter gets to 20 in each level
canvas.data.score += 1 #add to the score one point
redrawAll(canvas)
headRow,headCol = canvas.data.headRow, canvas.data.headCol
snakeBoard = canvas.data.snakeBoard
if (snakeBoard[headRow][headCol]>3): # if it had three food increase level
delay=400
else: delay = 500 # milliseconds
def f():
timerFired(canvas) # DK: define local fn in closure
canvas.after(delay, f) # pause, then call timerFired again
# draw the board and if game is over or paused prints the message
def redrawAll(canvas):
canvas.delete(ALL)
drawSnakeBoard(canvas)
printScore(canvas)
if (canvas.data.isGameOver == True):
cx = canvas.data.canvasWidth/2
cy = canvas.data.canvasHeight/2
highScores = canvas.data.highScores
cellSize = canvas.data.cellSize
canvas.create_rectangle(cx-3*cellSize,cy-2*cellSize,
cx+3*cellSize,cy+3*cellSize,fill="Yellow")
canvas.create_text(cx, cy-cellSize, text="Game Over!",
font=("Helvetica", 22, "bold"))
for i in xrange(len(highScores)):
canvas.create_text(cx,cy+i*cellSize,text="HIGHSCORE "+str(i+1)+": "+
str(highScores[i]),font=("Helvetica",18),fill="Red")
if (canvas.data.ispaused == True):
cx = canvas.data.canvasWidth/2
cy = canvas.data.canvasHeight/2
canvas.create_text(cx, cy, text="Paused!", font=("Helvetica",32,"bold"))
#prints the score
def printScore(canvas):
cx = canvas.data.canvasWidth/2
cy = canvas.data.margin + canvas.data.cellSize
score = canvas.data.score
canvas.create_text(cx, cy, text="SCORE:"+str(score),
font=("Helvetica", 24, "bold"), fill="Purple")
# draws every cell with appropraite color
def drawSnakeBoard(canvas):
snakeBoard = canvas.data.snakeBoard
rows = len(snakeBoard)
cols = len(snakeBoard[0])
for row in range(rows):
for col in range(cols):
drawSnakeCell(canvas,snakeBoard, row, col)
def rgbString(red, green, blue):
return "#%02x%02x%02x" % (red, green, blue)
#draws each cell with appropraite color and
#if the game is paused the color would be dimmed
def drawSnakeCell(canvas,snakeBoard, row, col):
margin = canvas.data.margin
cellSize = canvas.data.cellSize
left = margin + col * cellSize
right = left + cellSize
top = margin + row * cellSize + 2 * cellSize
bottom = top + cellSize
color = "white" if (not canvas.data.ispaused) else rgbString(100,100,100)
canvas.create_rectangle(left, top, right, bottom, fill=color)
if (snakeBoard[row][col] > 0):
# draw part of the snake body
color = "blue" if (not canvas.data.ispaused) else rgbString(0,0,100)
canvas.create_oval(left, top, right, bottom, fill=color)
elif (snakeBoard[row][col] == -1):
# draw food
color = "green" if (not canvas.data.ispaused) else rgbString(0,100,0)
canvas.create_oval(left, top, right, bottom, fill=color)
elif (snakeBoard[row][col] == -2):
# draw poison
color = "Red" if (not canvas.data.ispaused) else rgbString(100,0,0)
canvas.create_oval(left, top, right, bottom, fill=color)
elif (snakeBoard[row][col] == -3):
# draw wall
color ="Brown" if (not canvas.data.ispaused) else rgbString(180,140,140)
canvas.create_oval(left, top, right, bottom, fill=color)
# for debugging, draw the number in the cell
if (canvas.data.inDebugMode == True):
canvas.create_text(left+cellSize/2,top+cellSize/2,
text=str(snakeBoard[row][col]),font=("Helvatica",14,"bold"))
# initiates the board and snake to a cell in the middle of board
def loadSnakeBoard(canvas):
rows = canvas.data.rows
cols = canvas.data.cols
snakeBoard = [ ]
for row in range(rows): snakeBoard += [[0] * cols]
snakeBoard[rows/2][cols/2] = 1
canvas.data.snakeBoard = snakeBoard
findSnakeHead(canvas)
placeFood(canvas)
# place food (-1) in a random location on the snakeBoard, but
# keep picking random locations until we find one that is not
# part of the snake!
def placeFood(canvas):
snakeBoard = canvas.data.snakeBoard
rows = len(snakeBoard)
cols = len(snakeBoard[0])
headRow = canvas.data.headRow
headCol = canvas.data.headCol
while True:
row = random.randint(0,rows-1)
col = random.randint(0,cols-1)
if (snakeBoard[row][col] == 0):
break
snakeBoard[row][col] = -1
if snakeBoard[headRow][headCol]==4:
# if snakes eats three foods then it will go next level by adding poison
placePoison(canvas)
canvas.data.counter = 0
# place poison (-2) in a random location on the snakeBoard, but
# keep picking random locations until we find one that is not
# part of the snake, not on food place and also not exactly
# one after head of snake unless there is no other place!
def placePoison(canvas):
snakeBoard = canvas.data.snakeBoard
rows = len(snakeBoard)
cols = len(snakeBoard[0])
headRow = canvas.data.headRow
headCol = canvas.data.headCol
drow,dcol = canvas.data.snakeDrow,canvas.data.snakeDcol
while True:
row = random.randint(0,rows-1)
col = random.randint(0,cols-1)
# checks weheather there is no other option than putting
# the poison in front of snake head
if((snakeBoard[headRow][headCol]+2 == rows*cols) and
(snakeBoard[row][col] == 0)):
break
#checks not to put the poison in front of the snake head
if ((snakeBoard[row][col] == 0) and
not(row==headRow+drow and col==headCol+dcol)):
break
snakeBoard[row][col] = -2
# if we have a initial snake this might help to find snakes head
def findSnakeHead(canvas):
# find where snakeBoard[row][col] is largest, and
# store this location in headRow, headCol
snakeBoard = canvas.data.snakeBoard
rows = len(snakeBoard)
cols = len(snakeBoard[0])
headRow = 0
headCol = 0
for row in range(rows):
for col in range(cols):
if (snakeBoard[row][col] > snakeBoard[headRow][headCol]):
headRow = row
headCol = col
canvas.data.headRow = headRow
canvas.data.headCol = headCol
#prints instructions on the console
def printInstructions():
print "Snake!"
print "Use the arrow keys to move the snake."
print "Eat food to grow."
print "Stay on the board!"
print "And don't crash into yourself!"
print "Press 'd' for debug mode."
print "Press 'r' to restart."
def init(canvas):
printInstructions()
loadSnakeBoard(canvas)
canvas.data.inDebugMode = False
canvas.data.ispaused = False
canvas.data.isGameOver = False
canvas.data.snakeDrow = 0
canvas.data.snakeDcol = -1 # start moving left
canvas.data.ignoreNextTimerEvent = False
canvas.data.score = 0
canvas.data.counter = 0 #counts the moves after adding wall
canvas.data.isThereWall = False
redrawAll(canvas)
def run(rows, cols):
# create the root and the canvas
root = Tk()
margin = 5
cellSize = 30
canvasWidth = 2*margin + cols*cellSize
canvasHeight = 2*margin + rows*cellSize + 2 * cellSize
canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
canvas.pack()
# Store canvas in root and in canvas itself for callbacks
root.canvas = canvas.canvas = canvas
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.highScores = []
canvas.data.margin = margin
canvas.data.cellSize = cellSize
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.rows = rows
canvas.data.cols = cols
init(canvas)
# set up events
root.bind("<Button-1>",lambda event: mousePressed(canvas,event))
root.bind("<Key>",lambda event: keyPressed(canvas,event))
timerFired(canvas)
root.mainloop() # This call BLOCKS
run(16,16)
from Tkinter import *
import random
import copy
def mousePressed(canvas,event):
redrawAll(canvas)
def keyPressed(canvas,event):
if (event.char == "r"): # checks to restart the game when r pushed
init(canvas)
if (canvas.data.isGameOver == False):
if (event.keysym == "Down"):
moveFallingPiece(canvas,+1, 0) #push the peice one cell dwon
elif (event.keysym == "Left"):
moveFallingPiece(canvas,0,-1) #push the peice one cell left
elif (event.keysym == "Right"):
moveFallingPiece(canvas,0,+1) #push the peice one cell right
elif (event.keysym == "Up"):
rotateFallingPiece(canvas) #rotates the piece when up pushed
elif (event.keysym == "space"):
spaceFall(canvas)
elif (event.char == "z"):
canvas.data.zPressed = True
redrawAll(canvas)
# move the falling piece with drow and dcol and if that is not possible
# return to its previous place and return False so that if it is called with
# timerFired, it will know it reached to the buttom of board
def moveFallingPiece(canvas, drow, dcol):
canvas.data.fallingPieceRow = canvas.data.fallingPieceRow + drow
canvas.data.fallingPieceCol = canvas.data.fallingPieceCol + dcol
if (not fallingPieceIsLegal(canvas)):
canvas.data.fallingPieceRow = canvas.data.fallingPieceRow - drow
canvas.data.fallingPieceCol = canvas.data.fallingPieceCol - dcol
return False
return True
# checks if the piece is inside the board and it has nod collide
# with any other pieces
def fallingPieceIsLegal(canvas):
fallingPieceRow = canvas.data.fallingPieceRow
fallingPieceCol = canvas.data.fallingPieceCol
tetrisPiece=canvas.data.tetrisPiece
fallingPieceRows = len(tetrisPiece)
fallingPieceCols = len(tetrisPiece[0])
rows = canvas.data.rows
cols = canvas.data.cols
board = canvas.data.board
for row in range(fallingPieceRows):
for col in range(fallingPieceCols):
if (tetrisPiece[row][col]):
if (fallingPieceRow+row<0 or fallingPieceRow+row>=rows or
fallingPieceCol+col<0 or fallingPieceCol+col>=cols or
board[fallingPieceRow+row][fallingPieceCol+col]!="white"):
return False
return True
# rotates the falling piece and fixes the center of rotated piece
def rotateFallingPiece(canvas):
tetrisPieceOld=canvas.data.tetrisPiece
fallingPieceRows = len(tetrisPieceOld)
fallingPieceCols = len(tetrisPieceOld[0])
tetrisPiece = []
for row in range(fallingPieceCols): tetrisPiece+=[[False]*fallingPieceRows]
for row in range(fallingPieceRows):
for col in range(fallingPieceCols):
# rotate each cell to its new position and add it to the new piece
tetrisPiece[fallingPieceCols-col-1][row] = tetrisPieceOld[row][col]
canvas.data.tetrisPiece = tetrisPiece
fixCenter(canvas,fallingPieceRows,fallingPieceCols,tetrisPieceOld)
# fix the center of rotated piece
def fixCenter(canvas,fallingPieceRows,fallingPieceCols,tetrisPieceOld):
# delta shows the repositioning of rows and cols in fixing center
delta = (fallingPieceCols/2 - fallingPieceRows/2)
canvas.data.fallingPieceRow = (canvas.data.fallingPieceRow - delta
if abs(delta) > 0 else canvas.data.fallingPieceRow)
canvas.data.fallingPieceCol = (canvas.data.fallingPieceCol + delta
if abs(delta) > 0 else canvas.data.fallingPieceCol)
# if rotation is not legal means it is out of boundary or collide with
# other piece reload the original piece
if ( not fallingPieceIsLegal(canvas)):
canvas.data.tetrisPiece = tetrisPieceOld
canvas.data.fallingPieceRow = (canvas.data.fallingPieceRow + delta
if abs(delta) > 0 else canvas.data.fallingPieceRow)
canvas.data.fallingPieceCol = (canvas.data.fallingPieceCol - delta
if abs(delta) > 0 else canvas.data.fallingPieceCol)
# when peice reaches to a place which it can not go furthur
# it should add to the board
def placeFallingPiece(canvas):
board = canvas.data.board
rows = len(board)
cols = len(board[0])
tetrisPiece = canvas.data.tetrisPiece
tetrisPieceRows = len(tetrisPiece)
tetrisPieceCols = len(tetrisPiece[0])
fallingPieceRow = canvas.data.fallingPieceRow
fallingPieceCol = canvas.data.fallingPieceCol
tetrisPieceColor = canvas.data.tetrisPieceColor
for row in xrange (tetrisPieceRows):
for col in xrange (tetrisPieceCols):
# if the cell of piece has color then add it to the baord
if (tetrisPiece[row][col]):
board[fallingPieceRow+row][fallingPieceCol+col]=tetrisPieceColor
def timerFired(canvas):
delay = 450 # milliseconds
if (not canvas.data.isGameOver):
redrawAll(canvas)
# if the piece has reached to the buttom
if not moveFallingPiece(canvas,+1, 0):
placeFallingPiece(canvas) # add the piece to the board
removeFullRows(canvas) # remove all rows which are full
newFallingPiece(canvas) # make a new peice to start falling
# if there is no space for new falling piece then game is over
if (not fallingPieceIsLegal(canvas)):
canvas.data.isGameOver = True
# if game is over just redraw it
if (canvas.data.isGameOver):
redrawAll(canvas)
def f():
timerFired(canvas) # DK: define local fn in closure
canvas.after(delay, f) # pause, then call timerFired again
def redrawAll(canvas):
canvas.delete(ALL)
drawGame(canvas) # draws board and score board
# if the game is over print out Game Over in a yellow rectangle
if (canvas.data.isGameOver == True):
cx = canvas.data.canvasWidth/2
cy = canvas.data.canvasHeight/2
cellSize = canvas.data.cellSize
canvas.create_rectangle(cx-4*cellSize,cy-2*cellSize,
cx+4*cellSize,cy+2*cellSize,fill="Yellow")
canvas.create_text(cx,cy,text="Game Over!",font=("Helvetica",22,"bold"))
# if a row is full and there is no white cell in it remove it and
# add square number of removed rows to the score
def removeFullRows(canvas):
board = canvas.data.board
newBoard = [] # initiate a new board with removed full rows
rows = canvas.data.rows
cols = canvas.data.cols
for row in range(rows): newBoard += [["white"] * cols]
removeFullRows = 0 # shows the number of rows which has been removed
for row in xrange(rows):
oldRow = board[rows-row-1]
if "white" in oldRow: #if there is white in the row add it to the newboard
newBoard[rows-1-row+removeFullRows] = copy.copy(oldRow)
else: # if there is no white in the row ignore it and add to removed rows
removeFullRows += 1
canvas.data.board = newBoard
# add square number of removed rows to the score
canvas.data.score += removeFullRows ** 2
# draws board and score board
def drawGame(canvas):
drawBoard(canvas)
drawScore(canvas)
# draws score board
def drawScore(canvas):
score = canvas.data.score
cx = canvas.data.canvasWidth/2
cy = canvas.data.margin + canvas.data.cellSize
canvas.create_text(cx, cy, text="SCORE:"+str(score),
font=("Helvetica", 24, "bold"), fill="Purple")
# draws board and if game is not over the falling piece
def drawBoard(canvas):
board = canvas.data.board
rows = len(board)
cols = len(board[0])
cellSize = canvas.data.cellSize
margin = canvas.data.margin
canvas.create_rectangle(0,0,cols*cellSize+2*margin,
rows*cellSize+2*margin+ 2 * cellSize, fill="orange")
for row in range(rows):
for col in range(cols):
color=board[row][col]
# draws each cell with its color
drawCell(canvas,row,col,color)
if (not canvas.data.isGameOver):
drawFallingPiece(canvas)
# draws every cell with its appropraite color
def drawCell(canvas,row,col,color):
margin=canvas.data.margin
cellSize=canvas.data.cellSize
left = margin + col * cellSize
right = left + cellSize
top = margin + row * cellSize + 2 * cellSize
bottom = top + cellSize
canvas.create_rectangle(left, top, right, bottom, fill="black")
canvas.create_rectangle(left+2, top+2, right-2, bottom-2, fill=color)
# selects a random piece from tetris pieces
def newFallingPiece(canvas):
tetrisPieces = canvas.data.tetrisPieces
tetrisPiecesColors = canvas.data.tetrisPieceColors
if canvas.data.zPressed:
piece = len(tetrisPieces)-1
canvas.data.zPressed= False
else:
piece = random.randint(0,len(tetrisPieces)-2)
canvas.data.tetrisPiece = tetrisPieces [piece]
canvas.data.tetrisPieceColor = tetrisPiecesColors [piece]
fallingPieceRow = 0 # shows the row of upleft corner of falling piece
canvas.data.fallingPieceRow = fallingPieceRow
# shows the column of upleft corner of falling piece
fallingPieceCol = (canvas.data.cols - len(tetrisPieces [piece][0]))/2
canvas.data.fallingPieceCol = fallingPieceCol
# draws the falling piece on its related position with its own color
def drawFallingPiece(canvas):
tetrisPiece=canvas.data.tetrisPiece
fallingPieceRows = len(tetrisPiece)
fallingPieceCols = len(tetrisPiece[0])
fallingPieceRow = canvas.data.fallingPieceRow
fallingPieceCol = canvas.data.fallingPieceCol
color = canvas.data.tetrisPieceColor
for row in range(fallingPieceRows):
for col in range(fallingPieceCols):
if (tetrisPiece[row][col]):
drawCell(canvas,fallingPieceRow+row,fallingPieceCol+col,color)
def spaceFall(canvas):
b=True
while(b):
b=moveFallingPiece(canvas, +1, 0)
# initiates the pieces and their colors
def makePieces(canvas):
#Seven "standard" pieces (tetrominoes)
iPiece = [[ True, True, True, True]]
jPiece = [[ True, False, False ],[ True, True, True]]
lPiece = [[ False, False, True],[ True, True, True]]
oPiece = [[ True, True],[ True, True]]
sPiece = [[ False, True, True],[ True, True, False ]]
tPiece = [[ False, True, False ],[ True, True, True]]
zPiece = [[ True, True, False ],[ False, True, True]]
tetrisPieces = [ iPiece, jPiece, lPiece, oPiece, sPiece, tPiece, zPiece ]
tetrisPieceColors=["red","yellow","magenta","pink","cyan","green","orange"]
canvas.data.tetrisPieces = tetrisPieces
canvas.data.tetrisPieceColors = tetrisPieceColors
# initiates the board with all white cells
def loadBoard(canvas):
rows = canvas.data.rows
cols = canvas.data.cols
board = [ ]
for row in range(rows): board += [["white"] * cols]
canvas.data.board = board
# initiates the pieces, board and a falling piece
def init(canvas):
makePieces(canvas)
canvas.data.isGameOver = False
canvas.data.score = 0 # keeps scoring with initial value of zero
loadBoard(canvas)
canvas.data.zPressed = False
newFallingPiece(canvas)
redrawAll(canvas)
def run(rows, cols):
# create the root and the canvas
root = Tk()
margin = 15
cellSize = 20
canvasWidth = 2*margin + cols*cellSize
canvasHeight = 2*margin + rows*cellSize + 2 * cellSize
canvas = Canvas(root, width=canvasWidth, height=canvasHeight)
canvas.pack()
root.resizable(width=0, height=0)
# Store canvas in root and in canvas itself for callbacks
root.canvas = canvas.canvas = canvas
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.margin = margin
canvas.data.cellSize = cellSize
canvas.data.canvasWidth = canvasWidth
canvas.data.canvasHeight = canvasHeight
canvas.data.rows = rows
canvas.data.cols = cols
init(canvas)
# set up events
root.bind("<Button-1>",lambda event: mousePressed(canvas,event))
root.bind("<Key>",lambda event: keyPressed(canvas,event))
timerFired(canvas)
root.mainloop() # This call BLOCKS
run(20,20)
RECURSION - FRACTAL -( Koch Snowflake, Sirpinsky Triangulation)
# koch-snowflake.py
import turtle
def kN(length, n):
if (n == 1):
turtle.forward(length)
else:
kN(length/3.0, n-1)
turtle.left(60)
kN(length/3.0, n-1)
turtle.right(120)
kN(length/3.0, n-1)
turtle.left(60)
kN(length/3.0, n-1)
def kochSnowflake(length, n):
for step in range(3):
kN(length, n)
turtle.right(120)
turtle.delay(100)
turtle.speed(100)
turtle.penup()
turtle.goto(-300,100)
turtle.pendown()
turtle.penup()
turtle.goto(-250,50)
turtle.pendown()
turtle.pencolor("red")
kochSnowflake(200, 6)
turtle.done()
#Sierpinsky Triangle
from Tkinter import *
def drawSierpinskyTriangle(canvas, x, y, size, level):
x = float(x)
y = float(y)
if (level == 0):
canvas.create_polygon(x, y,
x+size, y,
x+size/2, y-size*(3**0.5)/2,
fill="black")
else:
drawSierpinskyTriangle(canvas, x, y, size/2, level-1)
drawSierpinskyTriangle(canvas, x+size/2, y, size/2, level-1)
drawSierpinskyTriangle(canvas, x+size/4, y-size*(3**0.5)/4, size/2, level-1)
def keyPressed(event):
if (event.keysym in ["Up", "Right"]):
canvas.data.level += 1
elif ((event.keysym in ["Down", "Left"]) and (canvas.data.level > 0)):
canvas.data.level -= 1
redrawAll()
def redrawAll():
canvas.delete(ALL)
drawSierpinskyTriangle(canvas, 25, 450, 450, canvas.data.level)
canvas.create_text(250, 25,
text = "Level %d Sierpinsky Triangle" % (canvas.data.level),
font = "Arial 26 bold")
canvas.create_text(250, 50,
text = "Use arrows to change level",
font = "Arial 10")
def init():
canvas.data.level = 1
redrawAll()
def run():# create the root and the canvas
global canvas
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
init()# set up events
#root.bind("<Button-1>", mousePressed)
root.bind("<Key>", keyPressed)
#timerFired()
root.mainloop() # This call BLOCKS (so your program waits until you close the window!)
run()
FRACTAL MICKERY MOUSE
fractalMickeyMouse(canvas, xc, yc, r, level) that recursively draws a character with the face you previously defined, and a recursively downsized version of that same face as ears.
from Tkinter import *
def fractalMickeyMouse(canvas, xc, yc, r, level):
xc, yc = float(xc), float(yc)
if (level == 0): # base case
canvas.create_oval(xc-r, yc-r, xc+r, yc+r, fill="white")
nose_delta_x,nose_delta_y = r/5, r/6
eye_delta_x, eye_delta_y = r/3 , r/2
mouth_delta = r-r/6
#for drawing MickeyMouse face without ear, it is just in first level
canvas.create_oval(xc-nose_delta_x, yc+nose_delta_y, xc+nose_delta_x ,
yc+nose_delta_y*2,fill="black")
canvas.create_oval(xc-eye_delta_x, yc-eye_delta_y, xc-eye_delta_x/3 ,
yc,fill="black")
canvas.create_oval(xc+eye_delta_x/3, yc-eye_delta_y, xc+eye_delta_x ,
yc,fill="black")
canvas.create_arc(xc-mouth_delta,yc-mouth_delta,xc+mouth_delta,
yc+mouth_delta,start=-15,extent=-150,style=ARC)
else: # recursive part is here that happens by increasing levels
delta = r * 3 * 2 ** (0.5) /4 # for finding the place of ears
fractalMickeyMouse(canvas, xc-delta, yc-delta, r/2, level-1)
fractalMickeyMouse(canvas, xc+delta, yc-delta, r/2, level-1)
def keyPressed(canvas,event):
if (event.keysym in ["Up", "Right"]):
canvas.data.level += 1
if canvas.data.level > 6: canvas.data.level=6
elif ((event.keysym in ["Down", "Left"]) and (canvas.data.level > 0)):
canvas.data.level -= 1
redrawAll(canvas)
def redrawAll(canvas):
canvas.delete(ALL)
for i in range(canvas.data.level+1):
fractalMickeyMouse(canvas, 230, 215, 100, i)
def init(canvas):
canvas.data.level = 0
redrawAll(canvas)
def run():
root = Tk()
width=460
height=330
canvas = Canvas(root, width=width, height=height, background="#005000")
canvas.pack()
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.width=width
canvas.data.height=height
init(canvas)
# set up events
#root.bind("<Button-1>", mousePressed)
root.bind("<Key>", lambda event: keyPressed(canvas,event))
#timerFired()
# and launch the app
root.mainloop()
run()
# runMotionAfterefffect
def runMotionAfterefffect(canvas, xc, yc, r):
numberOfArcs=16 #number of arcs in each slice
numberOfSlices=16 #number of slices in a circle
moveFactor = 8.0 #with how many time call resets the effect
time= canvas.data.time
for j in range(numberOfSlices+1):
fill = "black" if (time/int(moveFactor)+j)%2==0 else "white"
#draw the outer arc which starts to move in
canvas.create_arc(xc-r+r/numberOfArcs,yc-r+r/numberOfArcs,
xc+r-r/numberOfArcs,yc+r-r/numberOfArcs,
start=j*(360/numberOfSlices),extent=360/numberOfSlices,
style=ARC,width=r/numberOfArcs,outline=fill)
for i in range(numberOfArcs): # draw the rest of arcs
fill = "black" if (time/int(moveFactor)+i+j)%2==0 else "white"
canvas.create_arc(xc-i*(1-(time%moveFactor/100.0))*r/numberOfArcs,
yc-i*(1-(time%moveFactor/100.0))*r/numberOfArcs,
xc+i*(1-(time%moveFactor/100.0))*r/numberOfArcs,
yc+i*(1-(time%moveFactor/100.0))*r/numberOfArcs,
start=j*(360/numberOfSlices),extent=360/numberOfSlices,style=ARC,
width=r/numberOfArcs,outline=fill)
def redrawAll(canvas):
canvas.delete(ALL)
runMotionAfterefffect(canvas, canvas.data.width/2, canvas.data.height/2,
min(canvas.data.height,canvas.data.width)/2)
def timerFired(canvas):
redrawAll(canvas)
delay = 10 # milliseconds
canvas.data.time+=1
def f():
timerFired(canvas) # DK: define local fn in closure
canvas.after(delay, f) # pause, then call timerFired again
def init(canvas):
canvas.data.time=0
redrawAll(canvas)
def run():
root = Tk()
width=300.0
height=300.0
canvas = Canvas(root, width=width, height=height)
canvas.pack()
# Set up canvas data and call init
class Struct: pass
canvas.data = Struct()
canvas.data.width=width
canvas.data.height=height
init(canvas)
# set up events
timerFired(canvas)
# and launch the appol
root.mainloop()
run()
HORRIFIED LINE RUNNER (Final Project)
This project is about a player who is trying to escape from a witch who is following him. The runner should run in the environemnt which is full of different blocks that he should avoid hitting them and there are coins which he should collect as much as he can. He also could get powerups which give him the chance to increase his score by make him fast so he can run more distance, magnet which helps him to collect more coins and extra life which gives him another chance after hitting any of blocks to resume his run.
His final score will be based on distance and number of coins which he could collect during his run.
There are three different levels which are easy to hard and player can choose and play it.