RacketGame-DevUniverseGraphics
Project 2: Build a Snake Game | Racket Projects
3.36 min read
Md Nasim Sheikh
Games are great for learning because they force you to manage mutable state without becoming messy. In Racket, we do this functionally!
Advertisement
The "World" Concept
We define a State.
- Snake position (list of coordinates)
- Food position
- Direction
#lang racket
(require 2htdp/universe 2htdp/image)
(struct posn (x y) #:transparent)
(struct game (snake food dir) #:transparent)
(define SEG-SIZE 20)
(define WIDTH 400)
(define HEIGHT 400)
The Tick Handler (Game Logic)
Every "tick" (frame), we calculate the new world.
(define (next-state g)
(define head (first (game-snake g)))
(define new-head (move head (game-dir g)))
(if (equal? new-head (game-food g))
; Eat! Grow snake.
(game (cons new-head (game-snake g))
(posn (random 20) (random 20))
(game-dir g))
; Move!
(game (cons new-head (drop-last (game-snake g)))
(game-food g)
(game-dir g))))
The Draw Handler
Convert state to an image.
(define (draw-game g)
(place-image (circle 10 "solid" "green")
(* (posn-x (game-food g)) SEG-SIZE)
(* (posn-y (game-food g)) SEG-SIZE)
(empty-scene WIDTH HEIGHT)))
Start!
(big-bang (game (list (posn 10 10)) (posn 5 5) 'right)
(on-tick next-state 0.1)
(to-draw draw-game)
(on-key handle-key))
Advertisement
Summary
In 50 lines, we have a reactive game loop. Racket's universe handles the messy event loop, letting you focus purely on the logic: State -> State.
Quick Quiz
Which library provides the 'big-bang' function for creating interactive worlds?
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: