Created
July 5, 2024 05:24
-
-
Save lpabon/c057db18955139057b0431038b2addd3 to your computer and use it in GitHub Desktop.
Snake game done in ChatGTP4o for KaboonJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
kaboom({ | |
global: true, | |
fullscreen: true, | |
clearColor: [0, 0, 0, 1], | |
debug: true, | |
scale: 1, | |
}); | |
const SPEED = 240; | |
const TILE_SIZE = 20; | |
const INITIAL_SNAKE_LENGTH = 3; | |
let direction = vec2(1, 0); | |
let snake = []; | |
let food; | |
const bugSound = loadSound("bug", "/examples/sounds/bug.mp3") | |
volume(0.2); | |
function respawnFood() { | |
const x = Math.floor(rand(0, width() / TILE_SIZE)) * TILE_SIZE; | |
const y = Math.floor(rand(0, height() / TILE_SIZE)) * TILE_SIZE; | |
food = add([ | |
rect(TILE_SIZE, TILE_SIZE), | |
pos(x, y), | |
color(0, 1, 0), | |
'food', | |
]); | |
} | |
function initSnake() { | |
for (let i = 0; i < INITIAL_SNAKE_LENGTH; i++) { | |
const part = add([ | |
rect(TILE_SIZE, TILE_SIZE), | |
pos((INITIAL_SNAKE_LENGTH - i - 1) * TILE_SIZE, 0), | |
color(1, 1, 1), | |
'snake', | |
]); | |
snake.push(part); | |
} | |
} | |
function moveSnake() { | |
const head = snake[0]; | |
const newHeadPos = head.pos.add(direction.scale(TILE_SIZE)); | |
if ( | |
newHeadPos.x < 0 || newHeadPos.x >= width() || | |
newHeadPos.y < 0 || newHeadPos.y >= height() || | |
snake.some(part => part.pos.eq(newHeadPos)) | |
) { | |
// Game Over | |
go("gameover"); | |
return; | |
} | |
const newHead = add([ | |
rect(TILE_SIZE, TILE_SIZE), | |
pos(newHeadPos), | |
color(1, 1, 1), | |
'snake', | |
]); | |
snake.unshift(newHead); | |
if (newHead.pos.eq(food.pos)) { | |
play(bugSound); | |
destroy(food); | |
respawnFood(); | |
} else { | |
const tail = snake.pop(); | |
destroy(tail); | |
} | |
} | |
scene("game", () => { | |
direction = vec2(1, 0); | |
snake = []; | |
respawnFood(); | |
initSnake(); | |
onKeyPress('up', () => { | |
if (direction.y === 0) direction = vec2(0, -1); | |
}); | |
onKeyPress('down', () => { | |
if (direction.y === 0) direction = vec2(0, 1); | |
}); | |
onKeyPress('left', () => { | |
if (direction.x === 0) direction = vec2(-1, 0); | |
}); | |
onKeyPress('right', () => { | |
if (direction.x === 0) direction = vec2(1, 0); | |
}); | |
loop(0.05, moveSnake); | |
}); | |
scene("gameover", () => { | |
add([ | |
text("Game Over"), | |
pos(center().sub(0, 40)), | |
area(), | |
anchor("center"), | |
]); | |
add([ | |
text("Press Space to Restart"), | |
pos(center().add(0, 40)), | |
area(), | |
anchor("center"), | |
]); | |
onKeyPress("space", () => go("game")); | |
}); | |
go("game"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment