' Snake Game — ASCII grid with snake movement simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL grid(99) AS LONG
    LOCAL x AS LONG, y AS LONG, i AS LONG
    LOCAL snakeX(19) AS LONG, snakeY(19) AS LONG
    LOCAL len AS LONG, dir AS LONG
    LOCAL foodX AS LONG, foodY AS LONG
    LOCAL hit AS LONG, running AS LONG
    LOCAL s AS STRING

    PRINT "SNAKE GAME"
    PRINT "=========="
    PRINT ""

    FOR y = 0 TO 9
        FOR x = 0 TO 9
            grid(y * 10 + x) = 0
        NEXT x
    NEXT y

    len = 3
    snakeX(0) = 4: snakeY(0) = 5
    snakeX(1) = 3: snakeY(1) = 5
    snakeX(2) = 2: snakeY(2) = 5
    FOR i = 0 TO len - 1
        grid(snakeY(i) * 10 + snakeX(i)) = 1
    NEXT i

    foodX = 7: foodY = 5
    grid(foodY * 10 + foodX) = 2

    dir = 0
    running = 1

    PRINT "Initial state (1=snake, 2=food):"
    FOR y = 0 TO 9
        FOR x = 0 TO 9
            IF grid(y * 10 + x) = 0 THEN PRINT ".";
            IF grid(y * 10 + x) = 1 THEN PRINT "#";
            IF grid(y * 10 + x) = 2 THEN PRINT "@";
        NEXT x
        PRINT ""
    NEXT y
    PRINT ""

    PRINT "Snake moves right (simulation)..."
    PRINT ""

    FOR i = 1 TO 6
        FOR y = 0 TO 9
            FOR x = 0 TO 9
                grid(y * 10 + x) = 0
            NEXT x
        NEXT y

        FOR y = len - 1 TO 1 STEP -1
            snakeX(y) = snakeX(y - 1)
            snakeY(y) = snakeY(y - 1)
        NEXT y

        snakeX(0) = snakeX(0) + 1

        IF snakeX(0) = foodX AND snakeY(0) = foodY THEN
            INCR len
            foodX = foodX + 1
            IF foodX > 9 THEN foodX = 0
            PRINT "  Ate food! Length = "; len
        END IF

        hit = 0
        FOR y = 1 TO len - 1
            IF snakeX(0) = snakeX(y) AND snakeY(0) = snakeY(y) THEN hit = 1
        NEXT y
        IF snakeX(0) < 0 OR snakeX(0) > 9 THEN hit = 1
        IF snakeY(0) < 0 OR snakeY(0) > 9 THEN hit = 1

        IF hit THEN
            PRINT "  CRASH! Game over after "; i; " moves."
            running = 0
            EXIT FOR
        END IF

        FOR y = 0 TO len - 1
            grid(snakeY(y) * 10 + snakeX(y)) = 1
        NEXT y
        IF foodX >= 0 THEN grid(foodY * 10 + foodX) = 2

        FOR y = 0 TO 9
            FOR x = 0 TO 9
                IF grid(y * 10 + x) = 0 THEN PRINT ".";
                IF grid(y * 10 + x) = 1 THEN PRINT "#";
                IF grid(y * 10 + x) = 2 THEN PRINT "@";
            NEXT x
            PRINT ""
        NEXT y
        PRINT "  Move "; i; " complete."
        PRINT ""
    NEXT i

    IF running THEN PRINT "Snake simulation completed."

    FUNCTION = 0
END FUNCTION
