Dan Torop

Part 6: more succinct drawing, if and random

Continued from Emacs Lisp programming pt. 5.

A more succinct version of drawxy from last week

Moves the cursor to an arbitrary column x line y on screen and draws sprite.

(defun drawxy (x y sprite)
  (erase-buffer)
  (insert-char ?\n y)
  (insert-char ?\s x)
  (insert sprite))

Uses insert-char to space over. ?\s is the code for the space character. With insert-char you can specify the number of characters to insert, and don’t need a dotimes loop.

A more succinct version of background from last week

(defun background (width height)
  (erase-buffer)
  (dotimes (i height)
    (insert-char ?\. width)
    (newline)))

Uses insert-char to draw the grid, saving a dotimes. This draws a grid of periods (via ?\. character code). You could replace ?\. with ?\s to draw an invisible grid. Either way, the goal is to create a space in which the cursor will move, to draw multiple sprites without having to erase the buffer.

The drawxy2 function from last week, a touch briefer

(defun drawxy2 (x y sprite)
  (goto-char 1)
  (forward-line y)
  (forward-char x)
  (delete-region (point) (+ (point) (length sprite)))
  (insert sprite))

Using if

Depends on having background and drawxy2 already eval’d.

(defun where ()
  (background 40 25)
  (dotimes (i 10)
    (if (= i 5)
	(drawxy2 30 i "here")
      (drawxy2 (* i 3) (* i 2) "there?"))
    (sit-for 0.2)))

Using random

Also depends on having background and drawxy2 already eval’d.

(defun where2 ()
  (background 40 25)
  (dotimes (i 20)
    (if (= i 12)
	(drawxy2 30 i (propertize "here" 'face '(:foreground "green")))
      (drawxy2 (random 30) (random 25) "there?"))
    (sit-for 0.2)))

Continued in Emacs Lisp programming pt. 7.