Battleship Action

Warm-ups for the draw and mouse handler.

Grid Drawing System

We are going to set up a system to draw on a grid where each square is 50x50. You have probably done this before.

We want to take the list

(list (make-posn 5 2) (make-posn 4 3) (make-posn 3 2))

and draw it as

Ingredients:

  • gp->cp: posn -> posn. A function that takes grid coordinates and puts out the computer coordinates of the center of the grid square. You need to decide if the upper left is (0,0) or (1,1) (both are fine). I chose (0,0) as the upper left, which corresponds to a computer posn of (25,25).

      (check-expect (gp->cp (make-posn 1 2)) (make-posn 75 125))
    
  • draw-squares: list-of-posn(grid-posns) image(background) -> image. Draw grey squares at every grid posn, on top of the background image.

    The purpose of taking in an image background is to make it easier to make this function step by step. You can also use smaller backgrounds for your testing than you want to use for the real game.

  • draw-h: list-of-posn(grid-posns) -> image. Same as draw-squares, but pick a specific background.

Interactive Clicking

Now we want to place a grey square every time we click inside the grid box. The center of the square we place should be in the center of the grid square, regardless of whether we click in the middle or on the edge of the grid square.

Ingredients:

  • cp->gp: posn -> posn. A function to translate computer coordinates to grid coordinates. I am using (0,0) as the upper left:

      (check-expect (cp->gp (make-posn 28 107) (make-posn 0 2)))
    
  • mouse-h: A mouse handler using a list of posns for the model. Add the grid posn when you click.

(check-expect (mouse-h empty 28 107 "button-down")
              (list (make-posn 0 2)))

Combining

Put your functions together and make sure they work before you try to do something more complex.

(big-bang empty
  (on-draw draw-h)
  (on-mouse mouse-h))

Make sure the grid square lights up no matter where in the square you click.

Bonus

Add a key handler so that hitting backspace (key is "\b") removes the most recently placed square.

Last modified August 18, 2023: 2022-2023 End State (7352e87)