[source code] Pygame (Python Game Development) Tutorials 41-50

+3 Bucky Roberts · November 13, 2014
Pygame Tutorial 41
# THIS SCRIPT SHOULD BE CALLED SETUP.PY
import cx_Freeze

executables = [
# name of your game script
cx_Freeze.Executable("slither.py")
]
cx_Freeze.setup(
name = "Slither",
options = {"build_exe": {"packages":["pygame"],"include_files":["apple.png","snakehead.png"]}},
description = "Slither game tutorial",
executables = executables)


#python setup.py build
#python setup.py bdist_msi


Pygame Tutorial 42
import pygame
import time
import random

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')

icon = pygame.image.load('apple2.png')
pygame.display.set_icon(icon)

img = pygame.image.load('snakehead2.png')
appleimg = pygame.image.load('apple2.png')

clock = pygame.time.Clock()

AppleThickness = 30
block_size = 20
FPS = 15

direction = "right"

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)


def pause():

paused = True
message_to_screen("Paused",
black,
-100,
size="large")

message_to_screen("Press C to continue or Q to quit.",
black,
25)
pygame.display.update()

while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False

elif event.key == pygame.K_q:
pygame.quit()
quit()

#gameDisplay.fill(white)

clock.tick(5)


def score(score):
text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])

def randAppleGen():
randAppleX = round(random.randrange(0, display_width-AppleThickness))#/10.0)*10.0
randAppleY = round(random.randrange(0, display_height-AppleThickness))#/10.0)*10.0

return randAppleX,randAppleY



def game_intro():

intro = True

while intro:

for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Slither",
green,
-100,
"large")
message_to_screen("The objective of the game is to eat red apples",
black,
-30)

message_to_screen("The more apples you eat, the longer you get",
black,
10)

message_to_screen("If you run into yourself, or the edges, you die!",
black,
50)

message_to_screen("Press C to play, P to pause or Q to quit.",
black,
180)

pygame.display.update()
clock.tick(15)




def snake(block_size, snakelist):

if direction == "right":
head = pygame.transform.rotate(img, 270)

if direction == "left":
head = pygame.transform.rotate(img, 90)

if direction == "up":
head = img

if direction == "down":
head = pygame.transform.rotate(img, 180)


gameDisplay.blit(head, (snakelist[-1][0], snakelist[-1][1]))

for XnY in snakelist[:-1]:
pygame.draw.rect(gameDisplay, green, [XnY[0],XnY[1],block_size,block_size])

def text_objects(text,color,size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)


return textSurface, textSurface.get_rect()


def message_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg,color, size)
textRect.center = (display_width / 2), (display_height / 2)+y_displace
gameDisplay.blit(textSurf, textRect)


def gameLoop():
global direction

direction = 'right'
gameExit = False
gameOver = False

lead_x = display_width/2
lead_y = display_height/2

lead_x_change = 10
lead_y_change = 0

snakeList = []
snakeLength = 1

randAppleX,randAppleY = randAppleGen()

while not gameExit:

if gameOver == True:
message_to_screen("Game over",
red,
y_displace=-50,
size="large")

message_to_screen("Press C to play again or Q to quit",
black,
50,
size="medium")
pygame.display.update()


while gameOver == True:

for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = False
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()


for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = "left"
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
direction = "right"
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
direction = "up"
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
direction = "down"
lead_y_change = block_size
lead_x_change = 0

elif event.key == pygame.K_p:
pause()

if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
gameOver = True


lead_x += lead_x_change
lead_y += lead_y_change

gameDisplay.fill(white)


#pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, AppleThickness, AppleThickness])

gameDisplay.blit(appleimg, (randAppleX, randAppleY))


snakeHead = []
snakeHead.append(lead_x)
snakeHead.append(lead_y)
snakeList.append(snakeHead)

if len(snakeList) > snakeLength:
del snakeList[0]

for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead:
gameOver = True


snake(block_size, snakeList)

score(snakeLength-1)


pygame.display.update()

if lead_x > randAppleX and lead_x < randAppleX + AppleThickness or lead_x + block_size > randAppleX and lead_x + block_size < randAppleX + AppleThickness:

if lead_y > randAppleY and lead_y < randAppleY + AppleThickness:

randAppleX,randAppleY = randAppleGen()
snakeLength += 1

elif lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + AppleThickness:

randAppleX,randAppleY = randAppleGen()
snakeLength += 1









clock.tick(FPS)

pygame.quit()
quit()

game_intro()
gameLoop()


Pygame Tutorial 43
import pygame

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

gameDisplay = pygame.display.set_mode((800,600))

gameDisplay.fill(blue)

Pix = pygame.PixelArray(gameDisplay)

Pix[10][10] = green


while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

pygame.display.update()


Pygame Tutorial 44
import pygame

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

gameDisplay = pygame.display.set_mode((800,600))

gameDisplay.fill(blue)

Pix = pygame.PixelArray(gameDisplay)

Pix[10][10] = green

pygame.draw.line(gameDisplay, red, (200,300), (500,500),5)
pygame.draw.circle(gameDisplay, red, (200,200), 100)

pygame.draw.rect(gameDisplay, green,(150,150,200,100))
pygame.draw.polygon(gameDisplay, white, ((140,5),(200,16),(88,333),(600,222),(555,222)))


while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

pygame.display.update()


Pygame Tutorial 45
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (34,177,76)
clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
message_to_screen("Press C to play, P to pause or Q to quit",black,180)
pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()



gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()


Pygame Tutorial 46
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
yellow = (200,200,0)
green = (34,177,76)
clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
#message_to_screen("Press C to play, P to pause or Q to quit",black,180)

pygame.draw.rect(gameDisplay,green,(150,500,100,50))
pygame.draw.rect(gameDisplay,yellow,(350,500,100,50))
pygame.draw.rect(gameDisplay,red,(550,500,100,50))






pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()


gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()


Pygame Tutorial 47
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
yellow = (200,200,0)
green = (34,177,76)
clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
#message_to_screen("Press C to play, P to pause or Q to quit",black,180)

pygame.draw.rect(gameDisplay,green,(150,500,100,50))
pygame.draw.rect(gameDisplay,yellow,(350,500,100,50))
pygame.draw.rect(gameDisplay,red,(550,500,100,50))

text_to_button("play", black, 150,500,100,50)
text_to_button("controls", black, 350,500,100,50)
text_to_button("quit", black, 550,500,100,50)






pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()


gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()


Pygame Tutorial 48
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
yellow = (200,200,0)
green = (34,177,76)
light_green = (0,255,0)



clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
#message_to_screen("Press C to play, P to pause or Q to quit",black,180)


cur = pygame.mouse.get_pos()

if 150+100 > cur[0] > 150 and 500+50 > cur[1] > 500:
pygame.draw.rect(gameDisplay,light_green,(150,500,100,50))
else:
pygame.draw.rect(gameDisplay,green,(150,500,100,50))


pygame.draw.rect(gameDisplay,yellow,(350,500,100,50))
pygame.draw.rect(gameDisplay,red,(550,500,100,50))

text_to_button("play", black, 150,500,100,50)
text_to_button("controls", black, 350,500,100,50)
text_to_button("quit", black, 550,500,100,50)






pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()


gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()


Pygame Tutorial 49
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)


red = (200,0,0)
light_red = (255,0,0)

yellow = (200,200,0)
light_yellow = (255,255,0)

green = (34,177,76)
light_green = (0,255,0)



clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def button(text, x, y, width, height, inactive_color, active_color):
cur = pygame.mouse.get_pos()

if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
else:
pygame.draw.rect(gameDisplay, inactive_color, (x,y,width,height))

text_to_button(text,black,x,y,width,height)



def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
#message_to_screen("Press C to play, P to pause or Q to quit",black,180)


button("play", 150,500,100,50, green, light_green)
button("controls", 350,500,100,50, yellow, light_yellow)
button("quit", 550,500,100,50, red, light_red)



pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()


gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()


Pygame Tutorial 50
import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))


pygame.display.set_caption('Tanks')

#icon = pygame.image.load("apple.png")
#pygame.display.set_icon(icon)

white = (255,255,255)
black = (0,0,0)


red = (200,0,0)
light_red = (255,0,0)

yellow = (200,200,0)
light_yellow = (255,255,0)

green = (34,177,76)
light_green = (0,255,0)



clock = pygame.time.Clock()

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 85)

#img = pygame.image.load('snakehead.png')
#appleimg = pygame.image.load('apple.png')

def score(score):

text = smallfont.render("Score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])


def text_objects(text, color,size = "small"):

if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)

return textSurface, textSurface.get_rect()

def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)

def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)


def button(text, x, y, width, height, inactive_color, active_color):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1:
print("BUTTON CLICKED!!!")
else:
pygame.draw.rect(gameDisplay, inactive_color, (x,y,width,height))

text_to_button(text,black,x,y,width,height)



def pause():

paused = True
message_to_screen("Paused",black,-100,size="large")
message_to_screen("Press C to continue playing or Q to quit",black,25)
pygame.display.update()
while paused:
for event in pygame.event.get():

if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()



clock.tick(5)


def game_intro():

intro = True

while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
elif event.key == pygame.K_q:

pygame.quit()
quit()

gameDisplay.fill(white)
message_to_screen("Welcome to Tanks!",green,-100,size="large")
message_to_screen("The objective is to shoot and destroy",black,-30)
message_to_screen("the enemy tank before they destroy you.",black,10)
message_to_screen("The more enemies you destroy, the harder they get.",black,50)
#message_to_screen("Press C to play, P to pause or Q to quit",black,180)


button("play", 150,500,100,50, green, light_green)
button("controls", 350,500,100,50, yellow, light_yellow)
button("quit", 550,500,100,50, red, light_red)



pygame.display.update()

clock.tick(15)

game_intro()

def gameLoop():
gameExit = False
gameOver = False
FPS = 15

while not gameExit:

if gameOver == True:
#gameDisplay.fill(white)
message_to_screen("Game Over",red,-50,size="large")
message_to_screen("Press C to play again or Q to exit",black,50)
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameLoop()
elif event.key == pygame.K_q:

gameExit = True
gameOver = False



for event in pygame.event.get():

if event.type == pygame.QUIT:
gameExit = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pass

elif event.key == pygame.K_RIGHT:
pass

elif event.key == pygame.K_UP:
pass


elif event.key == pygame.K_DOWN:
pass

elif event.key == pygame.K_p:
pause()


gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)

pygame.quit()
quit()


gameLoop()

Post a Reply

Replies

Oldest  Newest  Rating
0 Edward Tran · December 19, 2014
Hello, I was not able to run the exe once the my .py file is built. When I press it, the cmd appears for a fraction of second and it closes. I tried to read what it was written in the cmd and "module object has no attribute" was written. Here is my code:

import pygame
import time
import random

## images
IMG_SNAKE = pygame.image.load("SnakeHead.png")
IMG_APPLE = pygame.image.load("Apple.png")
ICON = pygame.image.load("logo.png")

## colors
WHITE = (255,255,255)
BLACK= (0,0,0)
RED = (255,0,0)
GREEN = (0,100,0)
BLUE = (0,0,255)

## variables
NAME = "PySnake"
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
FPS = 15
BLOCK_SIZE = 20
APPLE_SIZE = 30
direction = "right"
lastDirection = direction

pygame.init()
gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH,DISPLAY_HEIGHT))
pygame.display.set_icon(ICON)
pygame.display.set_caption(NAME)

## object to control framerate
clock = pygame.time.Clock() 

## fonts
SMALL_FONT = pygame.font.SysFont("comicsansms", 25, True) 
MEDIUM_FONT = pygame.font.SysFont("comicsansms", 50, True) 
LARGE_FONT = pygame.font.SysFont("comicsansms", 80, True)

def getTextSurface(text,color,size):
    ## draw text on a new Surface
    if size == "small":
        textSurface = SMALL_FONT.render(text, True, color) 
    elif size == "medium":
        textSurface = MEDIUM_FONT.render(text, True, color)
    elif size == "large":
        textSurface = LARGE_FONT.render(text, True, color)
    return textSurface,textSurface.get_rect()
    
def blitText(msg,color,x_displace=0,y_displace=0,size="small"):
    ## draw surface on another surface
    textSurf, textRect = getTextSurface(msg,color,size)
    textRect.center = (DISPLAY_WIDTH/2) + x_displace, (DISPLAY_HEIGHT/2) + y_displace
    gameDisplay.blit(textSurf, textRect) 

def generateApple():
    applePositionX = round(random.randrange(0, DISPLAY_WIDTH - APPLE_SIZE))
    applePositionY = round(random.randrange(0, DISPLAY_HEIGHT - APPLE_SIZE))
    return applePositionX, applePositionY

def drawSnake(block_size, snakeList):
    ## rotate snake head according to direction variable
    if direction == "right":
        snakeHead = pygame.transform.rotate(IMG_SNAKE, 270)
    elif direction == "left":
        snakeHead = pygame.transform.rotate(IMG_SNAKE, 90)
    elif direction == "up":
        snakeHead = IMG_SNAKE
    elif direction == "down":
        snakeHead = pygame.transform.rotate(IMG_SNAKE, 180)

    ## draw head of snake    
    gameDisplay.blit(snakeHead, (snakeList[-1][0], snakeList[-1][1]))
    for coordinate in snakeList[:-1]: ## exclude last element 
        ## draw rectangle [x,y,w,h]
        pygame.draw.rect(gameDisplay, GREEN, [coordinate[0],coordinate[1],block_size,block_size])

def updateScore(score):
    text = SMALL_FONT.render("Score: "+str(score), True, BLACK)
    gameDisplay.blit(text, [0,0])

def pauseGame():
    paused = True

    while paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    paused = False
                elif event.key == pygame.K_q:
                    pygame.quit()
                    quit()
                    
##        gameDisplay.fill(WHITE)
        blitText("Pause", BLACK, y_displace=-100,size="large")
        blitText("Press C to continue or Q to quit", BLACK, 25)
        pygame.display.update()
        clock.tick(5) ## change FPS
    
def startScreen():
    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: #if quit button is pressed
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    intro = False
                    runGame()
                elif event.key == pygame.K_q:
                    pygame.quit()
                    quit()
                elif event.key == pygame.K_r:
                    showRule()
                        
        gameDisplay.fill(WHITE)
        blitText("PySnake", GREEN, y_displace=-100, size="large")
        blitText("by Edward Tran", BLACK, y_displace=0, x_displace=200, size="medium")
        blitText("Press C to play, R for rules, P to pause or Q to quit", BLACK, y_displace=180)
        pygame.display.update()
        clock.tick(15) ## change FPS

def showRule():
    inRule = True

    while inRule:
         for event in pygame.event.get():
            if event.type == pygame.QUIT: #if quit button is pressed
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_b:
                    inRule = False
                    startScreen()
                elif event.key == pygame.K_q:
                    pygame.quit()
                    quit()
         gameDisplay.fill(WHITE)
         blitText("HOW TO PLAY", RED, y_displace=-100, size="medium")
         blitText("The objective of the game is to eat red apples", BLACK, y_displace=-30)
         blitText("The more apples you eat, the longer you get", BLACK, y_displace=10)
         blitText("If you run into yourself, or the edges, you die!", BLACK, y_displace=50)
         blitText("Press B to go back or Q to quit", BLACK, y_displace=180)
         pygame.display.update()
         clock.tick(15)
         
def runGame():
    
    global direction ## to update direction
    global lastDirection
    gameExit = False
    gameOver = False

    ## x and y position of the snake head
    headPositionX = DISPLAY_WIDTH/2
    headPositionY = DISPLAY_HEIGHT/2

    headPositionXChange = BLOCK_SIZE
    headPositionYChange = 0

    snakeList = []
    snakeLength = 1

    applePositionX, applePositionY = generateApple()

    while not gameExit:
        
        while gameOver == True:
            gameDisplay.fill(WHITE)
            blitText("Game Over", RED, y_displace=-50, size="large")
            blitText("Press C to play again or Q to quit", BLACK, y_displace=50)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT: #if quit button is pressed
                    gameExit = True
                    gameOver = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    elif event.key == pygame.K_c:
                        direction = "right" 
                        runGame()
            
        for event in pygame.event.get(): ## loop through list of events
            if event.type == pygame.QUIT: ## if quit button is pressed
                gameExit = True
            if event.type == pygame.KEYDOWN:
                ## making sure snake can only move forward and not backward
                if event.key == pygame.K_LEFT and direction != "right":
                    headPositionXChange = -BLOCK_SIZE
                    headPositionYChange = 0
                    lastDirection = direction
                    direction = "left"
                elif event.key == pygame.K_RIGHT and direction != "left":
                    headPositionXChange = BLOCK_SIZE
                    headPositionYChange = 0
                    lastDirection = direction
                    direction = "right"
                elif event.key == pygame.K_UP and direction != "down":
                    headPositionYChange = -BLOCK_SIZE
                    headPositionXChange = 0
                    lastDirection = direction
                    direction = "up"
                elif event.key == pygame.K_DOWN and direction != "up":
                    headPositionYChange = BLOCK_SIZE
                    headPositionXChange = 0
                    lastDirection = direction
                    direction = "down"
                elif event.key == pygame.K_p:
                    pauseGame()
                            
        headPositionX += headPositionXChange
        headPositionY += headPositionYChange

        ## game over if snake goes outside screen size
        if headPositionX >= DISPLAY_WIDTH or  headPositionX < 0 or headPositionY >= DISPLAY_HEIGHT or headPositionY < 0:
            gameOver = True

        ## fix snake and apple overlapping 
        if headPositionX > applePositionX and headPositionX < applePositionX + APPLE_SIZE or headPositionX + BLOCK_SIZE > applePositionX and headPositionX + BLOCK_SIZE < applePositionX + APPLE_SIZE:
            if headPositionY > applePositionY and headPositionY < applePositionY + APPLE_SIZE or headPositionY + BLOCK_SIZE > applePositionY and headPositionY + BLOCK_SIZE < applePositionY + APPLE_SIZE:
                applePositionX, applePositionY = generateApple()
                snakeLength += 1

        gameDisplay.fill(WHITE) ## change background color
##        pygame.draw.rect(gameDisplay, RED, [applePositionX, applePositionY, APPLE_SIZE, APPLE_SIZE])
        gameDisplay.blit(IMG_APPLE, (applePositionX, applePositionY))
   
        snakeHead = []
        ## get head coordinate  
        snakeHead.append(headPositionX)
        snakeHead.append(headPositionY)
        ## append coordinate in list
        snakeList.append(snakeHead)

        if len(snakeList) > snakeLength: ## if there is more blocks allowed in snake, fix list 
            del snakeList[0]
        for eachSegment in snakeList[:-1]: ## if snake eats itself
            if eachSegment == snakeHead:
                ## making sure eating its head does not end the game
                if direction == "left" and lastDirection != "right" or direction == "right" and lastDirection != "left" or direction == "up" and lastDirection != "down" or direction == "down" and lastDirection != "up":
                    print(lastDirection + " " + direction)
                    gameOver = True
                
        drawSnake(BLOCK_SIZE, snakeList) 
        updateScore(snakeLength-1) ## score is snake length - 1
        pygame.display.update() ## update change
        clock.tick(FPS) 

    pygame.quit()
    quit()
    
startScreen()
  • 1

Python

106,978 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator