Advertisement
Guest User

Untitled

a guest
Jan 4th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 18.18 KB | None | 0 0
  1. #lang racket
  2.  
  3. #|
  4.    The Snake game
  5.    --------------
  6.  
  7.    The Snake game revolves around a room filled with pieces of radioactive goo
  8.    and a snake that can remove this goo.
  9.  
  10.    When the snake eats the goo, it grows and new goo appears. Like all
  11.    radioactive material, goo decays over time. Eventually it expires, but
  12.    fortunately for the snake, a new piece of goo appears elsewhere.
  13.  
  14.    The player is in control of a snake, and the objective is to grow the snake as
  15.    large as possible. She may change the direction of the snake by pressing one of
  16.    the four arrow keys. When the snake gets close to a piece of goo, it eats the
  17.    goo and grows a new segment. If the snake runs into itself or one of the four
  18.    walls, the game is over. The length of the snake is the player's score.
  19.  
  20.    Play
  21.    ----
  22.  
  23.    Run and evaluate
  24.      (start-snake)
  25.    This will pop up a window with instructions for interacting with the program.
  26. |#
  27.  
  28. ;
  29. ;
  30. ;
  31. ;
  32. ;                                 ;;
  33. ;     ;;; ;                        ;
  34. ;    ;   ;;                        ;
  35. ;    ;    ;   ;; ;;;      ;;;;     ;  ;;;     ;;;
  36. ;    ;         ;;   ;    ;    ;    ;  ;      ;   ;
  37. ;     ;;;;     ;    ;         ;    ; ;      ;     ;
  38. ;         ;    ;    ;    ;;;;;;    ;;;      ;;;;;;;
  39. ;    ;    ;    ;    ;   ;     ;    ;  ;     ;  
  40. ;    ;;   ;    ;    ;   ;    ;;    ;   ;     ;    ;
  41. ;    ; ;;;    ;;;  ;;;   ;;;; ;;  ;;  ;;;;    ;;;;
  42. ;
  43. ;
  44. ;
  45. ;
  46.  
  47. (require 2htdp/image 2htdp/universe)
  48. ;; -----------------------------------------------------------------------------
  49. ;; Data Definitions
  50.  
  51. ;; A Pit is a (pit Snake (Listof Goo))
  52.  
  53. (struct pit (snake goos) #:transparent)
  54.  
  55. ;; A Snake is a (make-snake Direction (cons Seg [Listof Seg]))
  56. (struct snake (dir segs score) #:transparent)
  57. ;; The head of the snake is the first element in the list of segs.
  58. ;; Each segment of a snake is located with:
  59. ;;  - x in (0,SIZE),
  60. ;;  - y in (0,SIZE).
  61. ;; And is SEG-SIZE aligned (x and y are multiples of SEG-SIZE).
  62.  
  63. ;; A Seg is a (posn Number Number)
  64.  
  65. ;; A Goo is a (goo Posn Number)
  66. (struct goo (loc expire) #:transparent)
  67. ;; The expire field is a Natural Number that represents the number
  68. ;; of ticks until the goo expires. A goo is expired when this field is 1
  69.  
  70. ;; A Direction is one of "up" "down" "left" "right"
  71.  
  72. ;; A Posn is (posn number number)
  73. (struct posn (x y) #:transparent)
  74. ;; Represents a two dimensional point.
  75.  
  76.  
  77. ;; -----------------------------------------------------------------------------
  78. ;; Constants
  79.  
  80. ;; Tick Rate
  81. (define TICK-RATE 0.2)
  82.  
  83. ;; Board Size Constants
  84. (define SIZE 20)
  85.  
  86. ;; Snake Constants
  87. (define SEG-SIZE 30)
  88.  
  89. ;; Goo Constants
  90. (define MAX-GOO 5)
  91. (define EXPIRATION-TIME 150)
  92.  
  93. ;; GRAPHICAL BOARD
  94. (define WIDTH-PX  (* SEG-SIZE 20))
  95. (define HEIGHT-PX (* SEG-SIZE 20))
  96.  
  97. ;; Visual constants
  98. (define MT-SCENE (empty-scene WIDTH-PX HEIGHT-PX))
  99. (define GOO-IMG (bitmap "graphics/goo.gif"))
  100. (define SEG-IMG  (bitmap "graphics/body.gif"))
  101. (define HEAD-IMG (bitmap "graphics/head.gif"))
  102.  
  103. (define HEAD-LEFT-IMG HEAD-IMG)
  104. (define HEAD-DOWN-IMG (rotate 90 HEAD-LEFT-IMG))
  105. (define HEAD-RIGHT-IMG (flip-horizontal HEAD-LEFT-IMG))
  106. (define HEAD-UP-IMG (flip-vertical HEAD-DOWN-IMG))
  107.  
  108. (define ENDGAME-TEXT-SIZE 26)
  109.  
  110. ;                                          
  111. ;                                          
  112. ;                                          
  113. ;                          ;              
  114. ;                          ;              
  115. ;  ;;;   ;;;                              
  116. ;   ;;   ;;                                
  117. ;   ; ; ; ;     ;;;;     ;;;      ;; ;;;  
  118. ;   ; ; ; ;    ;    ;      ;       ;;   ;  
  119. ;   ; ; ; ;         ;      ;       ;    ;  
  120. ;   ;  ;  ;    ;;;;;;      ;       ;    ;  
  121. ;   ;     ;   ;     ;      ;       ;    ;  
  122. ;   ;     ;   ;    ;;      ;       ;    ;  
  123. ;  ;;;   ;;;   ;;;; ;;  ;;;;;;;   ;;;  ;;;
  124. ;                                          
  125. ;                                          
  126. ;                                          
  127. ;                                          
  128. ;; -----------------------------------------------------------------------------
  129.  
  130. ;; Start the Game
  131. ;; старт программы. Вызывается фун. создания мира.
  132. (define (start-snake)
  133.   (big-bang
  134.       (pit (snake "right" (list (posn 1 1))0)
  135.                  (list (fresh-goo)
  136.                        ))
  137.            
  138.            ; (on-tick next-pit (begin (set!  TICK-RATE (/  TICK-RATE 2)) (begin
  139.      ;(display TICK-RATE) TICK-RATE)))
  140.             (on-tick next-pit TICK-RATE)
  141.             (on-key direct-snake)
  142.             (to-draw render-pit)
  143.             (stop-when dead? render-end)))
  144.  
  145. (define (tim  TICK-RATE)
  146.                   (set!  TICK-RATE (/  TICK-RATE 2)))
  147.  
  148. ;; Pit -> Pit
  149. ;; Проверяется есть ли яблоко и если есть выполняется действие
  150. (define (next-pit world)
  151.   (define snake (pit-snake world))
  152.   (define goos  (pit-goos world))
  153.   (define goo-to-eat (can-eat (pit-snake world) (pit-goos world)))
  154.   (if goo-to-eat
  155.       (pit (grow (pit-snake world)) (eat (pit-goos world) goo-to-eat (pit-snake world)))
  156.       (pit (slither (pit-snake world))  (pit-goos world))  ))
  157.  
  158. ;; если нажата одна из нужных клавиш то происходит действие
  159. (define (direct-snake w ke)
  160.   (cond [(dir? ke) (world-change-dir w ke)]
  161.         [else w]))
  162.  
  163. ;; Начинается рендер мира
  164. (define (render-pit w)
  165.     (define snakel (pit-snake w))
  166.  (overlay/align  "center" "top" (beside
  167.            (text "Score: " ENDGAME-TEXT-SIZE "black")
  168.            (text (number->string (koll snakel)) ENDGAME-TEXT-SIZE "black")
  169.            
  170.            )
  171.          
  172.   (snake+scene (pit-snake w)
  173.                (goo-list+scene (pit-goos w) MT-SCENE))
  174.  
  175.   ))
  176.  
  177. ;; проверка что змея умерла
  178. (define (dead? w)
  179.   (define snake (pit-snake w))
  180.   (or (self-colliding? snake) (wall-colliding? snake)))
  181.  
  182. ;; Pit -> Scene
  183. ;; produces a gameover image
  184. ;(define (render-end w)
  185.  ; (overlay (text "Game over" ENDGAME-TEXT-SIZE "black")
  186.   ;         (render-pit w)))
  187.  
  188. (define (render-end w)
  189. (define snake (pit-snake w))
  190.   (define snakel (pit-snake w))
  191.   (overlay (above (text "Game over" ENDGAME-TEXT-SIZE "orange")
  192.            (text "You score" ENDGAME-TEXT-SIZE "orange")
  193.            (text (number->string (koll snakel)) ENDGAME-TEXT-SIZE "orange")
  194.            
  195.            )
  196.           (render-pit w)
  197.           )
  198.  ;(display pit-score)
  199.   )
  200.  
  201. (define (koll sn)
  202.   (snake-score sn))
  203.  
  204. ;; узнает съела ли голова яблоко
  205. (define (can-eat snake goos)
  206.          (if (close? (snake-head snake) (first goos))
  207.                   (first goos)
  208.                   #f))
  209.            
  210.  
  211.  
  212. ;; Удаляется съединое яблоко и добовляется новое
  213. (define (eat goos goo-to-eat snake)
  214.   (cons (fresh-goo1 snake) (remove goo-to-eat goos)))
  215.  
  216. ;; Seg Goo -> Boolean
  217. ;; Is the segment close to the goo?
  218. ;; > (close? (posn 1 2) (goo (posn 1 2) 4))
  219. ;; #t
  220. (define (close? s g)
  221.   (posn=? s (goo-loc g)))
  222.  
  223. ;;Добовляет сигмент к змейки при съедином яблоке и увеличивает значение рекорда
  224. (define (grow sn)
  225.   (snake (snake-dir sn) (cons (next-head sn) (snake-segs sn)) (+ (snake-score sn) 1))
  226.   ) ;;когда кушает яблоко
  227.  
  228.  
  229. (define (plusgoo n)
  230.   (+ n 1))
  231.  
  232. ;; переводит змею на один фрагмент вперед
  233. (define (slither sn)
  234.   (snake (snake-dir sn)
  235.          (cons (next-head sn) (all-but-last (snake-segs sn))) (snake-score sn) ))
  236.  
  237. ;;взависимости от нажатой клавиши изменяет положение
  238. (define (next-head sn)
  239.   (define head (snake-head sn))
  240.   (define dir (snake-dir sn))
  241.   (cond [(string=? dir "up") (posn-move head 0 -1)]
  242.         [(string=? dir "down") (posn-move head 0 1)]
  243.         [(string=? dir "left") (posn-move head -1 0)]
  244.         [(string=? dir "right") (posn-move head 1 0)]))
  245.  
  246. ;; изменяет положение
  247. (define (posn-move p dx dy)
  248.   (posn (+ (posn-x p) dx)
  249.         (+ (posn-y p) dy)))
  250.  
  251. ;;Так как змея не съела яблоко то уничножает конец змеи
  252. (define (all-but-last segs)
  253.   (cond [(empty? (rest segs)) empty]
  254.         [else (cons (first segs)
  255.                     (all-but-last (rest segs)))]))
  256.  
  257. ;; -----------------------------------------------------------------------------
  258. ;; Rotting Goo
  259.  
  260. ;; [Listof Goo] -> [Listof Goo]
  261. ;; Renew and rot goos.
  262. ;(define (age-goo goos)
  263.  ; (rot (renew goos)))
  264.  
  265.  
  266.  
  267. ;; [Listof Goo] -> [Listof Goo]
  268. ;; Renew any rotten goos.
  269. ;(define (renew goos)
  270. ;  (cond [(empty? goos) empty]
  271. ;        [(rotten? (first goos))
  272. ;         (cons (fresh-goo) (renew (rest goos)))]
  273. ;        [else
  274. ;         (cons (first goos) (renew (rest goos)))]))
  275.  
  276. ;; [Listof Goo] -> [Listof Goo]
  277. ;; Rot all of the goos.
  278. ;(define (rot goos)
  279. ;  (cond [(empty? goos) empty]
  280. ;        [else (cons (decay (first goos))
  281. ;                    (rot (rest goos)))]))
  282.  
  283. ;; Goo -> Boolean
  284. ;; has the goo expired?
  285. ;; > (rotten? (goo 1 2) 0)
  286. ;; #t
  287. (define (rotten? g)
  288.   (zero? (goo-expire g)))
  289.  
  290. ;; Goo -> Goo
  291. ;; decreases the expire field of goo by one
  292. ;; > (decay (goo (posn 1 2) 2))
  293. ;; (goo (posn 1 2) 1)
  294. ;(define (decay g)
  295. ;  (goo (goo-loc g) (sub1 (goo-expire g))))
  296.  
  297. ;; Создает яблоко
  298. (define (fresh-goo)
  299.   (goo (posn (add1 (random (sub1 SIZE)))
  300.              (add1 (random (sub1 SIZE))))
  301.        EXPIRATION-TIME)
  302.  
  303.   )
  304.  
  305.  
  306. (define (fresh-goo1 snake)
  307.   (goo (posn (add1 (random (sub1 SIZE)))
  308.              (add1 (random (sub1 SIZE))))
  309.        EXPIRATION-TIME)
  310.  
  311.   )
  312. ;                                                                                                      
  313. ;                                                                                                      
  314. ;                                                                                                      
  315. ;                                                                                                      
  316. ;                                                                                                      
  317. ;   ;;; ;;;;
  318. ;    ;   ;
  319. ;    ;  ;       ;;;    ;;;   ;;;   ;;;; ;
  320. ;    ; ;       ;   ;    ;     ;   ;    ;;
  321. ;    ;;;;     ;     ;    ;   ;    ;
  322. ;    ;   ;    ;;;;;;;    ;   ;     ;;;;;
  323. ;    ;   ;    ;           ; ;           ;
  324. ;    ;    ;    ;    ;     ; ;     ;     ;
  325. ;   ;;;   ;;    ;;;;       ;      ;;;;;;
  326. ;                          ;
  327. ;                         ;
  328. ;                      ;;;;;
  329. ;                                                                                                      
  330. ;; -----------------------------------------------------------------------------
  331.  
  332. ;; String -> Boolean
  333. ;; Is the given value a direction?
  334. ;; > (dir? "up")
  335. ;; #t
  336. (define (dir? x)
  337.   (or (string=? x "up")
  338.       (string=? x "down")
  339.       (string=? x "left")
  340.       (string=? x "right"))
  341.   )
  342.  
  343. ;; Пороверяет два действия если нажата противоположная клавиша и меняет нажатую клавишу
  344. (define (world-change-dir w d)
  345.   (define the-snake (pit-snake w))
  346.   (cond
  347.          [(opposite-dir? (snake-dir the-snake) d)
  348.          w]
  349.    
  350.         [else
  351.          (pit (snake-change-dir the-snake d)
  352.               (pit-goos w))]))
  353.  
  354.  
  355.  
  356.  
  357. ;; проверяет нажата ли клавиша противополжноя приведушей
  358.  
  359. (define (opposite-dir? d1 d2)
  360.   (cond [(and (string=? "up" d1)
  361.               (string=? "down" d2))
  362.         true]
  363.         [(and (string=? "down" d1)
  364.               (string=? "up" d2))
  365.         true]
  366.         [(and (string=? "left" d1)
  367.               (string=? "right" d2))
  368.         true]
  369.         [(and (string=? "right" d1)
  370.               (string=? "left" d2))
  371.         true]
  372.         [else false]))
  373.  
  374.  
  375. ;
  376. ;
  377. ;
  378. ;
  379. ;                                      ;;
  380. ;   ;;;;;;                              ;
  381. ;    ;    ;                             ;
  382. ;    ;    ;     ;;;     ;; ;;;      ;;; ;     ;;;      ;;  ;;;
  383. ;    ;    ;    ;   ;     ;;   ;    ;   ;;    ;   ;      ;;;
  384. ;    ;;;;;    ;     ;    ;    ;   ;     ;   ;     ;     ;
  385. ;    ;  ;     ;;;;;;;    ;    ;   ;     ;   ;;;;;;;     ;
  386. ;    ;   ;    ;          ;    ;   ;     ;   ;           ;
  387. ;    ;    ;    ;    ;    ;    ;    ;   ;;    ;    ;     ;
  388. ;   ;;;   ;;    ;;;;    ;;;  ;;;    ;;; ;;    ;;;;     ;;;;;
  389. ;
  390. ;
  391. ;
  392. ;                                                                                            
  393. ;; -----------------------------------------------------------------------------
  394.  
  395. ;; Snake Scene -> Scene
  396. ;; Draws the snake onto the scene
  397. ;; > (snake+scene snake0 MT-SCENE)
  398. ;; (place-image SEG-IMG 8 8 MT-SCENE)
  399. (define (snake+scene snake scene)
  400.   (define snake-body-scene
  401.     (img-list+scene  (snake-body snake) SEG-IMG scene))
  402.   (define dir (snake-dir snake))
  403.   (img+scene (snake-head snake)
  404.              (cond [(string=? "up" dir) HEAD-UP-IMG]
  405.                    [(string=? "down" dir) HEAD-DOWN-IMG]
  406.                    [(string=? "left" dir) HEAD-LEFT-IMG]
  407.                    [(string=? "right" dir) HEAD-RIGHT-IMG])
  408.              snake-body-scene))
  409.  
  410. ;; рисует яблоки на сцене
  411. (define (goo-list+scene goos scene)
  412.   (define (get-posns-from-goo goos)
  413.     (cond [(empty? goos) empty]
  414.           [else (cons (goo-loc (first goos))
  415.                       (get-posns-from-goo (rest goos)))]))
  416.   (img-list+scene (get-posns-from-goo goos) GOO-IMG scene))
  417.  
  418. ;; отсылает отрисовщику элементы по очереди
  419. (define (img-list+scene posns img scene)
  420.   (cond [(empty? posns) scene]
  421.         [else (img+scene (first posns)
  422.                          img
  423.                          (img-list+scene (rest posns) img scene))]))
  424.  
  425. ;; отрисовывает элемент в нужной позиции
  426. (define (img+scene posn img scene)
  427.   (place-image img
  428.                (* (posn-x posn) SEG-SIZE)
  429.                (* (posn-y posn) SEG-SIZE)
  430.                scene))
  431.  
  432. ;                                                                                  
  433. ;                                                                                  
  434. ;                                                                                  
  435. ;                                                                                  
  436. ;                            ;;                                                    
  437. ;   ;;;;;;;                   ;               ;;;; ;                              
  438. ;    ;    ;                   ;              ;    ;;                              
  439. ;    ;    ;   ;; ;;;      ;;; ;             ;           ;;;;   ;; ;  ;      ;;;    
  440. ;    ;  ;      ;;   ;    ;   ;;             ;          ;    ;   ;; ;; ;    ;   ;  
  441. ;    ;;;;      ;    ;   ;     ;             ;               ;   ;  ;  ;   ;     ;  
  442. ;    ;  ;      ;    ;   ;     ;             ;   ;;;;;  ;;;;;;   ;  ;  ;   ;;;;;;;  
  443. ;    ;    ;    ;    ;   ;     ;             ;      ;  ;     ;   ;  ;  ;   ;        
  444. ;    ;    ;    ;    ;    ;   ;;              ;     ;  ;    ;;   ;  ;  ;    ;    ;  
  445. ;   ;;;;;;;   ;;;  ;;;    ;;; ;;              ;;;;;    ;;;; ;; ;;; ;; ;;    ;;;;  
  446. ;                                                                                  
  447. ;                                                                                  
  448. ;                                                                                  
  449. ;                                                                                  
  450. ;; -----------------------------------------------------------------------------
  451.  
  452. ;; проверка что змея сама себя укусила
  453. (define (self-colliding? sn)
  454.   (cons? (member (snake-head sn) (snake-body sn))))
  455.  
  456. ;; проверка что змея вышла за пределы сцены
  457. (define (wall-colliding? sn)
  458.   (define x (posn-x (snake-head sn)))
  459.   (define y (posn-y (snake-head sn)))
  460.   (or (= 0 x) (= x SIZE)
  461.       (= 0 y) (= y SIZE)))
  462.  
  463.  
  464.  
  465. ;                                                                                            
  466. ;                                                                                            
  467. ;                                                                                            
  468. ;                                                                                            
  469. ;                                                                                            
  470. ;     ;;;     ;;;  ;;; ;;;   ;;;  ;;;;;;;   ;;;;;     ;;;;;;;     ;;;     ;;;;;;   ;;;   ;;;
  471. ;      ;;      ;    ;   ;     ;      ;        ;          ;         ;;      ;    ;   ;     ;  
  472. ;     ;  ;     ;    ;    ;   ;       ;        ;          ;        ;  ;     ;    ;    ;   ;  
  473. ;     ;  ;     ;    ;     ; ;        ;        ;          ;        ;  ;     ;    ;     ; ;    
  474. ;     ;  ;     ;    ;      ;         ;        ;          ;        ;  ;     ;;;;;       ;    
  475. ;    ;;;;;;    ;    ;     ; ;        ;        ;    ;     ;       ;;;;;;    ;  ;        ;    
  476. ;    ;    ;    ;    ;    ;   ;       ;        ;    ;     ;       ;    ;    ;   ;       ;    
  477. ;   ;      ;   ;    ;   ;     ;      ;        ;    ;     ;      ;      ;   ;    ;      ;    
  478. ;  ;;;    ;;;   ;;;;   ;;;   ;;;  ;;;;;;;   ;;;;;;;;  ;;;;;;;  ;;;    ;;; ;;;   ;;   ;;;;;  
  479. ;                                                                                            
  480. ;                                                                                            
  481. ;                                                                                            
  482. ;
  483. ;; -----------------------------------------------------------------------------
  484. ;; Posn Posn -> Boolean
  485. ;; Are the two posns are equal?
  486. ;; > (posn=? (posn 1 1) (posn 1 1))
  487. ;; true
  488. (define (posn=? p1 p2)
  489.   (and (= (posn-x p1) (posn-x p2))
  490.        (= (posn-y p1) (posn-y p2))))
  491.  
  492. ;;Возращает позицию головы змеи
  493. (define (snake-head sn)
  494.   (car (snake-segs sn)))
  495.  
  496. ;; вовращает тело змеи без головы
  497. (define (snake-body sn)
  498.   (rest (snake-segs sn)))
  499.  
  500. ;; Snake Direction -> Snake
  501. (define (snake-change-dir sn d)
  502.   (snake d (snake-segs sn) (snake-score sn)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement