Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame,random
- pygame.init()
- display_width = 800
- display_height = 600
- black = (0,0,0)
- white = (255,255,255)
- red = (255,0,0)
- gameDisplay = pygame.display.set_mode((display_width,display_height))
- pygame.display.set_caption('Snake')
- clock = pygame.time.Clock()
- snakeIMG = pygame.image.load('snake.png')
- appleIMG = pygame.image.load('apple.png')
- bodyIMG = pygame.image.load('body.png')
- x = display_width * 0.5
- y = display_height * 0.5
- body_x = [x]
- body_y = [y]
- body_len = 0
- apple_x =20 * random.randint(0,39)
- apple_y =20 * random.randint(0,29)
- directions = {"Left":0,"Up":1,"Right":2,"Down":3}
- direction =directions["Right"]
- end = False
- def snake(x,y,body_x,body_y):
- gameDisplay.blit(snakeIMG, (x,y))
- for i in range(1,len(body_x)):
- gameDisplay.blit(bodyIMG, (body_x[i],body_y[i]))
- def apple(x,y):
- gameDisplay.blit(appleIMG, (x,y))
- def checking(x,y,apple_x,apple_y):
- if x == apple_x and y == apple_y:
- return True
- else:
- return False
- def end_of_game(x,y):
- if x >= display_width or x < 0 or y >= display_height or y < 0:
- print(x,y)
- return True
- else:
- return False
- def size_increasing(x,y,direction,body_x,body_y):
- if direction == 0:
- body_x.append(x+20)
- body_y.append(y)
- elif direction == 1:
- body_x.append(x)
- body_y.append(y+20)
- elif direction == 2:
- body_x.append(x-20)
- body_y.append(y)
- elif direction == 3:
- body_x.append(x)
- body_y.append(y-20)
- while not end_of_game(x,y):
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- end = True
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_LEFT and direction != directions["Right"]:
- direction = directions["Left"]
- elif event.key == pygame.K_RIGHT and direction != directions["Left"]:
- direction = directions["Right"]
- elif event.key == pygame.K_UP and direction != directions["Down"]:
- direction = directions["Up"]
- elif event.key == pygame.K_DOWN and direction != directions["Up"]:
- direction = directions["Down"]
- if direction == directions["Right"]:
- x=x+20
- for i in range(len(body_x)):
- body_x[i]+=20
- elif direction == directions["Left"]:
- x=x-20
- for i in range(len(body_x)):
- body_x[i]-=20
- elif direction == directions["Up"]:
- y=y-20
- for i in range(len(body_y)):
- body_y[i]-=20
- elif direction == directions["Down"]:
- y=y+20
- for i in range(len(body_y)):
- body_y[i]+=20
- gameDisplay.fill(white)
- if checking(x,y,apple_x,apple_y):
- apple_x =20 * random.randint(0,39)
- apple_y =20 * random.randint(0,29)
- size_increasing(x,y,direction,body_x,body_y)
- apple(apple_x,apple_y)
- else:
- apple(apple_x,apple_y)
- snake(x,y,body_x,body_y)
- pygame.display.update()
- clock.tick(15)
- pygame.quit()
- quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement