Lisp Game Programming <Step8-1>
shipのstateが爆発中の状態ではなく、且つshotがdeadの状態の時、zキーを押すとshotの発射位置を計算してshotのstateをaliveにし、shot音を出して16dotづつ移動するプログラム
;; step8 <Shot>
;; -----------------------------------------------------------------------------------------------
(defgeneric Move-shot (shot))
(defmethod Move-shot (shot)
(when (= (state shot) 1) ; shot is alive
(decf (y shot) (dy shot))) ; shot 16 dot up
(when (< (y shot) -32) ; out of screen
(setf (state shot) 0))) ; shot off
(defgeneric Set-shot (shot ship keystate))
(defmethod Set-shot (shot ship keystate)
(when (and (/= (state ship) 2) ; if ship is not explode
(= (state shot) 0) ; and shot is dead
(eql (z keystate) t)) ; and set z key
(setf (y shot) (- (y ship) (height shot))) ; set shot position
(setf (x shot) (x ship))
(setf (state shot) 1) ; shot on
(Play-sample *shot-sound*) ; shot sound
(setf (z keystate) nil))) ; reset z key
メインルーチンは以下
(defun Common-shooter ()
"main routine"
(sdl:with-init (sdl:sdl-init-video sdl:sdl-init-audio) ; use video and audio
(sdl:window 640 480 :position #(192 50) ; size 640*480, position x(192) y(50)
:title-caption "THE SHOOTER"
:icon-caption "THE SHOOTER"
:double-buffer T)
; :fullscreen T)
; step 3
(Initialize) ; graphics initialize
; step 5
(Set-font) ; set font
; step 2
(Open-sound) ; open audio and load sound data
; step 2
(Play-music *bg-music*) ; play music
; step 3 - 8
(let ((keystate (make-instance 'keystate)) ; step 6 add sentence
(game-field (make-instance 'game-field)) ; step 7 add sentence
(ship (make-instance 'entity :imageid 0 :id 0 :x 224 :y 416
:width 32 :height 32 :dx 4 :dy 4 :state 1))(
(score-ship (make-instance 'object :imageid 0 :id 0 :x 496 :y 128))
(shot (make-instance 'entity :imageid 0 :height 32 :dy 16 :id 1 :state 0)) ; step 8 add sentence
(mapchip (make-instance 'object :imageid 1 :id 0)))
(sdl:update-display)
(sdl:with-events (:poll)
(:quit-event ()
; step 2
(Stop-sound) ; sample and music stop
(Close-sound) ; close audio
t)
; step 6
(:key-down-event (:key key)
(if (sdl:key= key :SDL-KEY-ESCAPE)
(sdl:push-quit-event)
(Update-keystate key t keystate)))
(:key-up-event (:key key)
(Update-keystate key nil keystate))
(:idle ()
; Game body
; step 6
(Move-ship ship keystate)
; step 7
(Fix-ship-position ship game-field)
; step 8
(Move-shot shot)
(Set-shot shot ship keystate)
; step 4
(Scroll mapchip) ; scroll background
; step 3
(when (= (state ship) 1)
(Draw ship)) ; draw ship
; step 8
(when (= (state shot) 1)
(Draw shot)) ; draw shot
; step 5
(Score-panel score-ship) ; draw score panel
(sdl:update-display))))))
こんな感じでzキーを押すと音を出してshotが上に移動していく