Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

Administrator / pygame_lesson3_diy1

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Members
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Switch branch/tag
  • pygame_lesson3_diy1
  • snake.py
Find file
BlameHistoryPermalink
  • BellCodeEditor's avatar
    save project · c341b5c9
    BellCodeEditor committed 3 years ago
    c341b5c9
snake.py 2.05 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
import pygame
from pygame import locals
from random import *
pygame.init()
screen = pygame.display.set_mode((660, 480))
FPSCLOCK = pygame.time.Clock()
background = pygame.image.load('bg.png')
right = pygame.image.load('right.png')
food = pygame.image.load('apple.png')
body = pygame.image.load('body.png')
left = pygame.image.load('left.png')
up = pygame.image.load('up.png')
down = pygame.image.load('down.png')
x, y = 240, 120
position = [(180,90),(180,120),(210,120),(x, y)]
setheading = "right"
snake_head = right
apple_x = randint(0,630)
apple_y = randint(0,430)
changdu=4
while apple_x%30!=0 or apple_y%30!=0:
    apple_x = randint(0,630)
    apple_y = randint(0,430)
while True:
    for event in pygame.event.get():
        if event.type == locals.QUIT:
            exit()
        if event.type == locals.KEYDOWN:
            if event.key == locals.K_RIGHT and setheading != "left":
                setheading = 'right'
                snake_head = right
            if event.key == locals.K_LEFT and setheading != "right":
                setheading = 'left'
                snake_head = left
            if event.key == locals.K_UP and setheading != "down":
                setheading = 'up'
                snake_head = up
            if event.key == locals.K_DOWN and setheading != "up":
                setheading = 'down'
                snake_head = down
    if setheading == "right":
        x += 30
    elif setheading == "left":
        x -= 30
    elif setheading == "up":
        y -= 30
    else:
        y += 30
    if x==apple_x and y==apple_y:
        changdu+=1
        apple_x = randint(0,630)
        apple_y = randint(0,430)
        while apple_x%30!=0 or apple_y%30!=0:
            apple_x = randint(0,630)
            apple_y = randint(0,430)
    position.append((x, y))
    if not changdu>=len(position):
        position.pop(0)
    screen.blit(background, (0, 0))
    screen.blit(snake_head, position[-1])
    for i in range(len(position)-1):
        screen.blit(body, position[i])
    screen.blit(food, (apple_x, apple_y))
    pygame.display.update()
    FPSCLOCK.tick(14)