Snake Game in Python:
import pygame
import random,sys
pygame.init()
clock = pygame.time.Clock()
#SCREEN
screen = pygame.display.set_mode((800,600))
#CAPTION
pygame.display.set_caption("SNAKE GAME")
#SNAKE KI POSITIONS
snake_pos = [[400,300],[420,300],[440,300]]
#APPLE KI POSITION
#apple_pos = [100,100]
apple_pos = [(random.randint(100,700)//20)*20, (random.randint(100,500)//20)*20]
#SCORE
score = 0
#DIRECTIONS
step = 20
up = (0, -step)
left = (-step,0)
right = (step,0)
down = (0,step)
direction = left
#FONT
font = pygame.font.SysFont('Arial', 30)
timer = 0
running = True
while running:
screen.fill((20,150,20))
#EVENT FETCHER
for event in pygame.event.get():
#QUIT
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit(0)
#KEYDOWN
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
print("UP")
direction = up
if event.key == pygame.K_DOWN:
print("DOWN")
direction = down
if event.key == pygame.K_LEFT:
print("LEFT")
direction = left
if event.key == pygame.K_RIGHT:
print("RIGHT")
direction = right
#snake_pos = [[snake_pos[0][0]+direction[0], snake_pos[0][1] + direction[1]]]+snake_pos[:-1]
timer += 1
if timer == 6:
snake_pos = [[snake_pos[0][0]+direction[0], snake_pos[0][1] + direction[1]]]+snake_pos[:-1]
timer = 0
#IF SNAKE EATS APPLE
if snake_pos[0] == apple_pos:
apple_pos = [(random.randint(100,700)//20)*20, (random.randint(100,500)//20)*20]
snake_pos.append(snake_pos[-1])
score += 1
#SNAKE DEATH
for i in range(1, len(snake_pos)):
if snake_pos[0] == snake_pos[i]:
print("DEAD!")
running = False
pygame.quit()
sys.exit(0)
#VERTICAL BOUNDARY
if 800 <= snake_pos[0][0] or snake_pos[0][0] <= 0:
print("DEAD!")
running = False
pygame.quit()
sys.exit(0)
#HORIZONTAL BOUNDARY
if 0 >= snake_pos[0][1] or snake_pos[0][1] >= 600:
print("DEAD!")
running = False
pygame.quit()
sys.exit(0)
#SNAKE PRINT
for x,y in snake_pos:
pygame.draw.circle(screen, (0,0,200), (x,y), 10)
#APPLE PRINT
pygame.draw.circle(screen, (200,0,0), apple_pos, 10)
#pygame.draw.circle(screen, (0,0,200), (400,300), 10)
#pygame.draw.circle(screen, (0,0,200), (420,300), 10)
#pygame.draw.circle(screen, (0,0,200), (440,300), 10)
#SCORE PRINT
text = font.render( "SCORE: " + str(score), True, (255,255,255) )
screen.blit(text, (0,0))
clock.tick(30)
pygame.display.update()
No comments:
Post a Comment