snake.py

Created by 4244

Created on August 28, 2025

1.3 KB

kkl


from kandinsky import *
from ion import *
from time import sleep

# Schermgrootte
W, H = 320, 222

# Startpositie slang
snake = [(80, 60)]
dx, dy = 10, 0  # beweegrichting
food = (150, 100)

def draw():
    fill_rect(0, 0, W, H, (255, 255, 255))  # achtergrond
    for x, y in snake:
        fill_rect(x, y, 10, 10, (0, 200, 0))  # slang
    fill_rect(food[0], food[1], 10, 10, (200, 0, 0))  # eten

def new_food():
    from random import randint
    return (10*randint(0, W//10 - 1), 10*randint(0, H//10 - 1))

while True:
    # Besturing pijltjes
    if keydown(KEY_UP) and dy == 0:
        dx, dy = 0, -10
    if keydown(KEY_DOWN) and dy == 0:
        dx, dy = 0, 10
    if keydown(KEY_LEFT) and dx == 0:
        dx, dy = -10, 0
    if keydown(KEY_RIGHT) and dx == 0:
        dx, dy = 10, 0

    # Nieuwe koppositie
    head = (snake[0][0] + dx, snake[0][1] + dy)

    # Check botsing met muren of zichzelf
    if (head[0] < 0 or head[0] >= W or
        head[1] < 0 or head[1] >= H or
        head in snake):
        draw_string("GAME OVER!", 100, 100, (255, 0, 0), (255, 255, 255))
        break

    # Voeg nieuwe kop toe
    snake.insert(0, head)

    # Check eten
    if head == food:
        food = new_food()
    else:
        snake.pop()  # verwijder staart

    draw()
    sleep(0.1)
# Type your text here

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.