使用paint-callback在Scheme中的现有画布上绘制新对象

时间:2014-04-21 22:56:51

标签: oop canvas scheme racket

有些背景,我将Space Invaders作为CS类中的项目。目前我正致力于让玩家发射射击弹,而不用担心碰撞,只是产生射弹。

(define projectile%
(class object%
(init-field [image (make-bitmap 10 10)]
            [x 100]
            [y 100]
            [speed 1])
(define/public (get-image) image)
(define/private (move-up)
  (set! y (- y speed)))
(define/public (render dc)
  (let ((w (send image get-width))
        (h (send image get-height)))
    (move-up)
    (send dc translate (+ x (/ w 2)) (+ y (/ h 2)))
    (send dc draw-bitmap image (- (/ w 2)) (- (/ h 2)))
    (send dc translate (- (+ x (/ w 2))) (- (+ y (/ h 2))))))
(super-new)))



(define player-ship%
  (class object%
    (init-field [image (make-bitmap 30 25)]
            [x 400]
            [y 300]
            [speed 3])
(define/public (get-image) image)
(define/public (get-x) x)
(define/public (get-y) y)
(define/private (shoot)  
  ;Spawning a projectile would go here
(define/public (render dc)
  (let ((w (send image get-width))
        (h (send image get-height)))
    (send dc translate (+ x (/ w 2)) (+ y (/ h 2)))
    (send dc draw-bitmap image (- (/ w 2)) (- (/ h 2)))
    (send dc translate (- (+ x (/ w 2))) (- (+ y (/ h 2))))))
(define/public (key-down key-code)
  (cond ((equal? key-code 'left) (move-left))
        ((equal? key-code 'right) (move-right))
        ((equal? key-code 'up) (shoot))))
(super-new)))

这是两个相关的类,一些失败的代码用于产生一个射弹被移除。

有关我如何绘制窗口和内容的一些代码:

(define *my-game-canvas*
  (new game-canvas%
       [parent *game-window*]
       [paint-callback (lambda (canvas dc)
                         (begin
                           (send *my-ship* render dc)
                           (send *ship-projectile* render dc)))]
       [keyboard-handler (lambda (key-event)
                           (let ((key-code (send key-event get-key-code)))
                             (if (not (equal? key-code 'release))
                                 (send *my-ship* key-down key-code))))]))
(define *my-timer* (new timer%
                        [notify-callback (lambda ()
                                           (send *my-game-canvas* refresh))]))

(make-ship-projectile (send *ship-projectile* get-image))
;creating a projectile just seeing whether they work or not
(make-ship (send *my-ship* get-image))

制造船和制造船的弹丸功能如下:

(define (make-ship-projectile bitmap-target)
 (let ((dc (new bitmap-dc% [bitmap bitmap-target])))
    (send dc set-brush (make-object brush% "black" 'solid))
    (send dc draw-ellipse 0 0 10 10)))

当我尝试用玩家出货率中的射击方法创建一个新的射弹时出现问题,它根本不起作用。我现在假设它不起作用,因为新的射弹不在 my-game-canvas 的绘画回调中,但是,我做不知道如何更新该属性。我是从错误的方向接近它吗?

1 个答案:

答案 0 :(得分:2)

是的,如果未从paint-callback(或从其调用的其他函数/方法)触发射弹的绘制,则在刷新画布时,它不会显示在画布中。

一种可能性是拥有现有射弹的列表(可能是player-ship%中的属性),paint-callback应触发(可能通过player-ship% render方法,或通过player-ship%中的render-projectiles中的另一种方法(从paint-callback调用)在画布中显示所有这些射弹。当从船上射出新的射弹时,应将其添加到现有射弹列表中,当射弹击中某物或逃离棋盘时,应将其从该列表中移除。