// Snake: a small game in a window. Arrow keys steer, Escape quits. use gui, random fun main() { size = 20 // one cell in pixels cols = 24 rows = 18 window = new.window("Snake", cols * size, rows * size) window.background("black") snake = [[5, 9], [4, 9], [3, 9]] // head first, each cell is [x, y] dx = 1 dy = 0 food = [random(0 to cols - 1), random(0 to rows - 1)] score = 0 while (window.open()) { if (window.key_down("left") and dx != 1) { dx = -1; dy = 0 } if (window.key_down("right") and dx != -1) { dx = 1; dy = 0 } if (window.key_down("up") and dy != 1) { dx = 0; dy = -1 } if (window.key_down("down") and dy != -1) { dx = 0; dy = 1 } if (window.key_down("escape")) { break } head = [snake[0][0] + dx, snake[0][1] + dy] hit_wall = head[0] < 0 or head[0] >= cols or head[1] < 0 or head[1] >= rows hit_self = false for (part in snake) { if (part[0] == head[0] and part[1] == head[1]) { hit_self = true } } if (hit_wall or hit_self) { window.alert("Game over! Score: " + score) break } snake.insert(0, head) if (head[0] == food[0] and head[1] == food[1]) { score += 1 food = [random(0 to cols - 1), random(0 to rows - 1)] } else { snake.pop() } window.clear() window.color("red") window.circle(food[0] * size + size / 2, food[1] * size + size / 2, size / 2 - 2) window.color("green") for (part in snake) { window.rect(part[0] * size + 1, part[1] * size + 1, size - 2, size - 2) } window.color("white") window.print("Score: " + score, 6, 4) window.sleep(0.12) } window.close() }