import pygame
import sys
import random
# Inisialisasi Pygame
pygame.init()
# Variabel global
WIDTH, HEIGHT = 600, 500
GRID_SIZE = 20
FPS = 10
# Warna
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Membuat layar game
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Inisialisasi snake
snake_size = 1
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
direction = 'RIGHT'
change_to = direction
speed = GRID_SIZE
# Inisialisasi makanan
food_pos = [random.randrange(1, (WIDTH//GRID_SIZE)) * GRID_SIZE,
random.randrange(1, (HEIGHT//GRID_SIZE)) * GRID_SIZE]
food_spawn = True
# Menggambar snake dan makanan
def draw_elements():
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, WHITE, pygame.Rect(pos[0], pos[1], GRID_SIZE,
GRID_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], GRID_SIZE,
GRID_SIZE))
# Memeriksa tabrakan
def check_collision():
if snake_pos[0] < 0 or snake_pos[1] < 0 or snake_pos[0] >= WIDTH or
snake_pos[1] >= HEIGHT:
game_over()
for segment in snake_body[1:]:
if snake_pos == segment:
game_over()
# Menjalankan game over
def game_over():
pygame.quit()
sys.exit()
# Memulai game loop
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
elif event.key == pygame.K_DOWN:
change_to = 'DOWN'
elif event.key == pygame.K_LEFT:
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
# Mengganti arah hanya jika arah baru bukan ke arah yang berlawanan dengan arah
sekarang
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
# Pembaruan posisi snake
if direction == 'UP':
snake_pos[1] -= speed
if direction == 'DOWN':
snake_pos[1] += speed
if direction == 'LEFT':
snake_pos[0] -= speed
if direction == 'RIGHT':
snake_pos[0] += speed
# Menambahkan kepala baru
snake_body.insert(0, list(snake_pos))
# Memeriksa apakah snake memakan makanan
if snake_pos == food_pos:
food_spawn = False
else:
snake_body.pop()
# Menypawn makanan baru
if not food_spawn:
food_pos = [random.randrange(1, (WIDTH//GRID_SIZE)) * GRID_SIZE,
random.randrange(1, (HEIGHT//GRID_SIZE)) * GRID_SIZE]
food_spawn = True
# Memeriksa tabrakan
check_collision()
# Menggambar elemen-elemen di layar
draw_elements()
pygame.display.flip()
clock.tick(FPS)