Skip to main content

Snake

Downloads

Lade hier das gesamte Projekt herunter

Download: Snake

Codeabschnitte

import Befehle
import pygame
import random
import os
Snake
def draw_square(column, row, color):
screen_x = column * SQUARE_SIZE
screen_y = row * SQUARE_SIZE
pygame.draw.rect(screen, color, (screen_x, screen_y, SQUARE_SIZE, SQUARE_SIZE))
Highscore
def load_highscore():
if os.path.exists("highscore.txt"):
with open("highscore.txt", "r") as file:
return int(file.read().strip())
return 0

def save_highscore(score):
with open("highscore.txt", "w") as file:
file.write(str(score))
Variablen
GROESSE = 900
SQUARE_COUNT = 20
SQUARE_SIZE = GROESSE / SQUARE_COUNT
START_LENGTH = 5
DELAY = 100

screen = pygame.display.set_mode((GROESSE, GROESSE))
pygame.display.set_caption("Snake")

score = 0
highscore = load_highscore()

font = pygame.font.SysFont("Arial", 30, bold=True) # score / highscore schrift
Variablen
head_column = SQUARE_COUNT // 2
head_row = SQUARE_COUNT // 2
snake_length = START_LENGTH
body_parts = []
step_x = 0
step_y = 0
apple_row = random.randint(0, SQUARE_COUNT - 1)
apple_column = random.randint(0, SQUARE_COUNT - 1)
Steuerung
    for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and step_x != -1:
step_x = 1
step_y = 0
elif keys[pygame.K_LEFT] and step_x != 1:
step_x = -1
step_y = 0
elif keys[pygame.K_UP] and step_y != 1:
step_x = 0
step_y = -1
elif keys[pygame.K_DOWN] and step_y != -1:
step_x = 0
step_y = 1
größer werdende Snake
body_parts.append((head_column, head_row))
if len(body_parts) > snake_length:
body_parts.pop(0)
Score erhöht sich
    if head_column == apple_column and head_row == apple_row:
snake_length += 1
score += 10 # +10 macht pro Apfel (punkte )
apple_row = random.randint(0, SQUARE_COUNT - 1)
apple_column = random.randint(0, SQUARE_COUNT - 1)
Wenn die Snake an die Wand kommt oder in sich selber fährt
    if (head_column, head_row) in body_parts[:-1] or head_column < 0 or head_column >= SQUARE_COUNT or head_row < 0 or head_row >= SQUARE_COUNT:
if score > highscore:
highscore = score
save_highscore(highscore)

score = 0
head_column = SQUARE_COUNT // 2
head_row = SQUARE_COUNT // 2
snake_length = START_LENGTH
body_parts = []
step_x = 0
step_y = 0

screen.fill((0, 0, 0))
Zeichnen der Snake
draw_square(head_column, head_row, (137, 207, 240))
for part in body_parts:
draw_square(part[0], part[1], (119, 190, 238))

draw_square(apple_column, apple_row, (255, 0, 0))
Highscore anzeigen
score_text = font.render(f"Aktueller Score: {score} | Highscore: {highscore}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))
Spielfeld / Grid zeichnen
    for i in range(SQUARE_COUNT):
line_pos = SQUARE_SIZE * i
pygame.draw.line(screen, (32, 32, 32), (line_pos, 0), (line_pos, GROESSE), 1)
pygame.draw.line(screen, (32, 32, 32), (0, line_pos), (GROESSE, line_pos), 1)