import random
import pygame
import sys
from pygame.locals import *
from os import system
system("pause")
Snakespeed = 7
Window_Width = 800
Window_Height = 500
Cell_Size = 20# Width and height of the cells
# Ensuring that the cells fit perfectly in the window. eg if cell size was
# 10    and window width or windowheight were 15 only 1.5 cells would # fit.
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
# Ensuring that only whole integer number of cells fit perfectly in the  window.
assert Window_Height % Cell_Size == 0, "Window height must be a multipl e of cell size."
Cell_W = int(Window_Width / Cell_Size)  # Cell Width
Cell_H = int(Window_Height / Cell_Size)  # Cellc Height
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)  # Defining element colors for the program.
Green = (0, 255, 0)
DARKGreen = (0, 155, 0)
DARKGRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)
BGCOLOR = Black  # Background color
UP = 'up'
DOWN = 'down'# Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'
HEAD = 0# Syntactic sugar: index of the snake's head
def main():
global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
SnakespeedCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height) )
BASICFONT = pygame.font.Font('f', 18)
pygame.display.set_caption('Snake')
showStartScreen()
while True:
runGame()
showGameOverScreen()
def runGame():
# Set a random start point.
startx = random.randint(5, Cell_W - 6)
starty = random.randint(5, Cell_H - 6)
wormCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT
# Start the apple in a random place.
apple = getRandomLocation()
while True:  # main game loop
for event in ():  # event handling loop
pe == QUIT:
terminate()
pe == KEYDOWN:
if (event.key == K_LEFT) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
# check if the Snake has hit itself or the edge
if wormCoords[HEAD]['x'] == -
1or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -
1or wormCoords[HEAD]['y'] == Cell_H:
return# game over
for wormBody in wormCoords[1:]:
if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
return# game over
# check if Snake has eaten an apply
if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y' ] == apple['y']:
# don't remove worm's tail segment
apple = getRandomLocation()  # set a new apple somewhere else:
del wormCoords[-1]  # remove worm's tail segment
# move the worm by adding a segment in the direction it is movi ng
if direction == UP:
newHead = {'x': wormCoords[HEAD]['x'],
'y': wormCoords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x': wormCoords[HEAD]['x'],
'y': wormCoords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x': wormCoords[HEAD][
'x'] - 1, 'y': wormCoords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x': wormCoords[HEAD][
'x'] + 1, 'y': wormCoords[HEAD]['y']}
wormCoords.insert(0, newHead)
DISPLAYSURF.fill(BGCOLOR)
drawGrid()
drawWorm(wormCoords)
drawApple(apple)
drawScore(len(wormCoords) - 3)
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
def drawPressKeyMsg():
pressKeySurf = der('Press a key to play.', True, White )
pressKeyRect = _rect()
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
def checkForKeyPress():
if len((QUIT)) > 0:
terminate()
keyUpEvents = (KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def showStartScreen():random python
titleFont = pygame.font.Font('f', 100)
titleSurf1 = der('Snake!', True, White, DARKGreen)
degrees1 = 0
degrees2 = 0
while True:
DISPLAYSURF.fill(BGCOLOR)
rotatedSurf1 = ate(titleSurf1, degrees1)        rotatedRect1 = _rect()
< = (Window_Width / 2, Window_Height / 2)
DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
drawPressKeyMsg()
if checkForKeyPress():
()  # clear event queue
return
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
degrees1 += 3# rotate by 3 degrees each frame
degrees2 += 7# rotate by 7 degrees each frame
def terminate():
pygame.quit()
def getRandomLocation():
return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
def showGameOverScreen():
gameOverFont = pygame.font.Font('f', 100)
gameSurf = der('Game', True, White)
overSurf = der('Over', True, White)
gameRect = _rect()
overRect = _rect()
gameRect.midtop = (Window_Width / 2, 10)
overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
DISPLAYSURF.blit(gameSurf, gameRect)
DISPLAYSURF.blit(overSurf, overRect)
drawPressKeyMsg()
pygame.display.update()
pygame.time.wait(500)
checkForKeyPress()  # clear out any key presses in the event queue
while True:
if checkForKeyPress():
()  # clear event queue
return
def drawScore(score):
scoreSurf = der('Score: %s' % (score), True, White)    scoreRect = _rect()
DISPLAYSURF.blit(scoreSurf, scoreRect)
def drawWorm(wormCoords):
for coord in wormCoords:
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。