Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- rebol [title: "Snake"]
- snake-game-object: context [
- readme: {
- Snake
- original code by Nick Antonaccio at re-bol.com
- written in rebol rebol.com
- }
- snake: to-image layout/tight [box red 10x10 edge none]
- food: to-image layout/tight [box green 10x10 edge none] ;[1]
- the-score: 0 direction: 0x10 newsection: false random/seed now
- dq: [0x10] ;direction queue; future directions ;[2]
- rand-pair: func [s] [
- to-pair rejoin [(round/to random s 10) "x" (round/to random s 10)]
- ]
- ;b is the image that is drawn in the rebol draw dialect
- ;its structure is 'image <actual image> position 'image <actual image> position ...
- ;b/3 is apple position. b/6 is snake head position
- b: reduce [
- 'image food ((rand-pair 190) + 50x50)
- 'image snake 150x150
- 'image snake 150x160 ;[5]
- ]
- view/new win: layout [
- scrn: box white 300x300 effect [draw b] rate 20
- origin across h2 "Score:"
- score: h2 bold "000000"
- do [focus scrn]
- ]
- scrn/feel/engage: func [f a e] [
- if a = 'key [
- ;dq direction queue, d direction
- unless find [up down left right] e/key [exit]
- d: select [up 0x-10 down 0x10 left -10x0 right 10x0] e/key
- if not equal? last dq negate d [append dq d] ;[3] prevents turning directly backwards
- ]
- if a = 'time [
- direction: either 1 = length? dq [first dq] [take dq] ;[4]
- ;If snake hits self or wall
- if any [b/6/1 < 0 b/6/2 < 0 b/6/1 > 290 b/6/2 > 290] [
- alert "You hit the wall!" unview/only win
- ]
- if find (at b 7) b/6 [alert "You hit yourself!" unview/only win]
- ;If an apple is eaten
- if within? b/6 b/3 10x10 [
- append b reduce ['image snake (last b)]
- newsection: true
- b/3: (rand-pair 290)
- the-score: the-score + 1
- score/text: to-string the-score
- ]
- ;create new image b
- newb: copy/part head b 5 append newb (b/6 + direction)
- for item 7 (length? head b) 1 [
- either (type? (pick b item) = pair!) [
- append newb pick b (item - 3)
- ] [
- append newb pick b item
- ]
- ]
- if newsection = true [
- clear (back tail newb)
- append newb (last b)
- newsection: false
- ]
- ;show new image
- b: copy newb
- show scrn
- ]
- ]
- scrn/text: None ;[6]
- ;set global
- set 'snake-game scrn
- do-events
- doc: {
- Alterations
- added direction queue to replace single direction variable.
- This means all key events are actioned whereas
- beforehand if two key events were close together only the second one would be actioned.
- Also changed code so snake cannot backtrack on itself.
- Minor alterations - score changed when apple is eaten.
- Set scrn/text to none to remove white cursor artifact
- added comments
- changed images to green and red boxes
- Possible evolutions
- enable replay
- replace alert code. Just replace replace the draw code with something.
- }
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement