TweetFollow Us on Twitter

Tic-Tac-Toe
Volume Number:1
Issue Number:12
Column Tag:Lisp Listener

Windows and Tic-Tac-Toe!

By Andy Cohen, Human Factors Engineer, MacTutor Contributing Editor

This month the Lisp Listener will feature a program written by Dean Ritz of ExperTelligence. The program is a Tic-Tac-Toe game which uses all of the functions described in previous issues. However, before discussing the game I'd like to present a subject long overdue.

Menus In ExperLisp

Creating a menu on the menu bar is actually a pretty straight forward, though nonintuitve, operation. In creating a menu one must use one of the special "hooks" in ExperLisp. There are also hooks for printing. Those will eventually be covered in future installments. The first step in creating a menu must be the identification of what the menu items will do. Menu items can call functions or perform assignment. If the items call defined functions, these functions should already be defined and the function names known. One then defines a function which returns a menu and a menu item on the condition that a certain menu and item position is selected. One easy way to do this uses a conditional which has not yet been discussed.

SELECTQ acts like COND since it has a clause and returns something based on the value of the clause. The first item following the term SELECTQ is the key-form . Each of the test items which follow are evaluated and the one which is the equivalent of the key-form causes the return of it's corresponding value or list. For example;

(defun what (x)
  (selectq x
           (1 'one)
           (2 'two)
           (t 'all)))

(what 1)
one
(what 3)
all

In the above, the selectq evaluates the passed value (x) for equality with the first atoms of each of the three following lists. If the atom is equal to the passed value, the atom following the first is returned. As in COND the "t" forces the return of the atom "all". In assigning menu item positions one may have a SELECTQ within a SELECTQ. The first level SELECTQ finds the menu, the second finds the menu item. For example:

(defun menuselect (themenu theitem)
  (selectq themenu
     (10 (selectq theitem
           (1 (function1B))
           (2 (function2B))
           (3 (function3B))))
     (11 (selectq theitem 
           (1 (function1A))
           (2 (function2A))
           (3 (function3A))))))

The first SELECTQ locates which group of items belong to the menu number assigned to "themenu". The second SELECTQ locates the item belonging to the item number assigned to "theitem". After one generates the above defined function one must assign the values returned by the function to the special menu-hook;

(setq ªmenuhook menusel)

One then assigns a label to the "NEWMENU" function (It is a built in function) and it's elements. This must be done with the ID number that one wants to assign to the menu as well as the menu title. For example:

(setq mymenu (newmenu 10 "menu B"))

Using this label one then assigns the item labels to the menu as follows:

(appendmenu mymenu "function1B")
(appendmenu mymenu "function2B")
(appendmenu mymenu "function3B")

or one may do it all in one list as follows:

(appendmenu mymenu " function1B; function2B;
function3B")

One then inserts the menu with:

(insertmenu mymenu 0)

Then draws it with:

(drawmenubar)

The entire sample with dummy functions follows:

(defun function1A ()
  (print "function 1A"))

(defun function2A ()
  (print "function 2A"))

(defun function3A ()
  (print "function 3A"))

(defun function1B ()
  (print "function 1B"))

(defun function2B ()
  (print "function 2B"))

(defun function3B ()
  (print "function 3B"))




(defun menuselect (themenu theitem)
  (selectq themenu
     (10 (selectq theitem
           (1 (function1B))
           (2 (function2B))
           (3 (function3B))))
     (11 (selectq theitem 
           (1 (function1A))
           (2 (function2A))
           (3 (function3A))))))

(setq ªmenuhook menuselect)

(setq mymenu (newmenu 10 "menu B")
      grmenu (newmenu 11 "menu A"))

(appendmenu grmenu 
«function1A;function2A;function3A»)
(appendmenu mymenu
 "function1B;function2B;function3B")


(insertmenu grmenu 0)       ;0=the beforeID #
(insertmenu mymenu 0)

(drawmenubar)

Note that in the INSERTMENU lists I used "0" as the before ID number. The number zero indicates that I want to place the menu to the right of any already existing menus.

One may call any of the six defined functions by selecting a menu item rather then by typing the function name into the Listener Window. We can see now that an application in ExperLisp can consist of a large number of functions which do not necessarily call each other. A function, when called, can provide some service on data or graphics as a stand alone utility. The operator can then change the data or graphics by calling up another function from the menu.

Another menu example follows:

(Defun number (x)
   (cond ((= 1 x) '(the number is one))
          ((= 2 x) '(the number is two))
          ((= 3 x) '(the number is three))
          ((= 4 x) '(the number is four))
          ((= 5 x) '(the number is five))
          ((= 6 x) '(the number is six))
          ((= 7 x) '(the number is seven))
          ((= 8 x) '(the number is eight))
          ((= 9 x) '(the number is nine))
          ((= 10 x) '(the number is ten))))
          
(defun order (themenu theitem)
  (if (not (eq nil std_graf)) (std_graf 'selectwindow))
  (selectq themenu
     (10 (selectq theitem 
           (1 (number 1))
           (2 (number 2))
           (3 (number 3))
           (4 (number 4))
           (5 (number 5))
           (6 (number 6))
           (7 (number 7))
           (8 (number 8))
           (9 (number 9))
           (10 (number 10))))))
     
(setq ªmenuhook order)

(setq mymenu (newmenu 10 "numbers"))

(appendmenu mymenu «one; two; three; four;
              four; five; six; seven; eight; nine; ten»)

(insertmenu mymenu 0)

(drawmenubar)

Deleting A Menu

Deleting a menu is easily accomplished by using the built in DELETEMENU and DISPOSEMENU functions. DELETEMENU actually deletes the menu from the menu bar. DISPOSEMENU releases the memory used by the just deleted menu. One should then redraw the menu bar with DRAWMENUBAR.

(deletemenu 10)
(disposemenu mymenu)
(drawmenubar)

Tic-Tac-Toe

While the following has very little that has not been discussed in previous Lisp Listener installments, there is a lot which is in different form. For example the use of SETQ for multiple assignment. ExperLisp accepts the spaces between the symbols and the stuff assigned to them as dividers. However, these spaces are ignored by ExperLisp whether they consist of one space, mutiple spaces or one line. Therefore, one may make multiple assignment in a formatted manner for easier reading. See PLACES below.

In the function named "random.choice" MEMQ is used. MEMQ is similar to MEMBER. Where member tests to see if the given atom is a member of a list using EQUAL, MEMQ uses EQ. EQUAL test equality of characters regardless of whether they are upper case or lower case. EQ returns "t" only if the two items are virtually identical. MEMQ returns the same as MEMBER (that is, when the tested atom is contained in the tested list it is returned along with all the atoms which followed it in the list tested for the membership).

PUSH (used in defined function "Player2") is similar to APPEND. It does a CONS of the item following into a list.

Figure 1 is the functional breakdown of the Tic-Tac-Toe game. TOE calls WINNER? and PLAYERS which return values. TOE also calls DRAWBOARD which does what it's title suggests. Both WINNER? and PLAYERS refer to subfunctions which use subsubfunctions. WINNER? calculates whether or not the game was either won or was a draw by looking at the number of moves made. If WINNER? returns nil then there is no winner yet and PLAYERS is called. PLAYERS checks to the current player's turn and calls either PLAYER1 or PLAYER2 based on which turn it is. PLAYER1 is the computer's moves. It uses NEXT.MOVE, WINNIN.MOVE and RANDOM.CHOICE to generate the move. Player2 uses POSITION and PT.IN.RECT to allow the human player to enter a move using the mouse. To start the game enter "(TOE)" into the Listener Window.

;**************************
;Tic-Tac-Toe wrtten by Dean Ritz
;PLACES is a list of pairs.  The first element of each  
;list of pairs represents the position (1-9).  The last 
;second element in each list of pairs is a boundary
;list for the piece which fits into that position.
;TURN remembers whose turn it is (player 1 or 2).
;WINS is a list of the 8 possible winning sets.  The
;program checks possible moves against this list.
;*********************************
(defun toe ()
  (setq 
    p1 nil 
    p2 nil ;Set the chosen positions to empty lists.
    places '((1 (-85 -85 -35 -35)) (2 (-85 -25 -35 25)) 
             (3 (-85 35 -35 85)) (4 (-25 -85 25 -35 )) 
             (5 (-25 -25 25 25)) (6 (-25 35 25 85)) 
             (7 (35 -85 85 -35)) (8 (35 -25 85 25)) 
             (9 (35 35 85 85)))
    wins '((1 2 3) (4 5 6) (7 8 9) (1 4 7) (2 5 8) 
           (3 6 9) (1 5 9) (3 5 7))
    turn 1
    std_graf (newgrafwindow '(45 5 320 500)))
  (send std_graf 'setwtitle "Tic Tac Toe")
  (send std_graf 'showwindow)
  (send std_graf 'selectwindow)
  (textface 0)
  (drawboard)
  (while (not (winner?)) (players))
  (cond ((check wins p2)
         (fillrect '(-110 -201 10 -100) white)
         (moveto -200 0)
         (drawstring "You win!!"))
        ((check wins p1)
         (fillrect '(-110 -201 10 -100) white)
         (moveto -200 0) 
         (drawstring "The Macintosh wins!!"))
        (t
          (fillrect '(-110 -201 10 -100) white)
          (moveto -200 0) 
          (drawstring "Cat's game.")))
  (dotimes (i 1800) (add1 3))
  (std_graf 'closewindow)
  (setq std_graf nil))

;**************************************
(defun drawboard ()
 (pendown)
 (penpat gray)
 (framerect '(-90 -90 90 90))
 (framerect '(-90 -32 90 32))
 (framerect '(-32 -90 32 90))
 (penpat black))

;**************************************
;WINNER? uses brute force to see if their is a
; winner.  If turn is 1, then it checks
; to see if player 2 won the game
; with the last move.



(defun winner? ()
  (cond ((< 8 (+ (length p1) (length p2))) t)
        ((and (= turn 1)
              (check wins p2)) 2)
        (t 
          (and (check wins p1) 1))))

;**************************************
(defun check (for against)
  (cond ((null for) nil)
        ((members (car for) against) t)
        (t (check (cdr for) against))))

;**************************************
;MEMBERS works recursively to see if all of the
;elements of the list :L1
;are members of the list :L2.

(defun members (l1 l2)
  (cond ((null l1) t)
        ((memq (car l1) l2)
         (members (cdr l1) l2))))

;**************************************
;This toggles the variables which determines whose
; turn it is.

(defun players ()
  (cond ((= turn 1)
         (player1) 
         (setq turn 2))
        (t 
          (player2) 
          (setq turn 1))))

;**************************************
;This runs the computer player's move.

(defun player1 (&aux choice)
  (fillrect '(-110 -201 10 -100) white)
  (moveto -200 0) (drawstring "Macintosh")
  (setq choice (next.move)
        p1 (cons choice p1))
  (filloval (car (last (assq choice places))) ltgray))

;**************************************
;this is the psuedo brains of the whole thing.  The
; goal is first to select a move that wins, then
; select a move that blocks,
;otherwise just select any untaken shot.

(defun next.move ()
  (prog (tempo)
        (setq tempo (winning.move 1 p1))
        (if tempo (return tempo))
        (setq tempo (winning.move 1 p2))
        (if tempo (return tempo))
        (random.choice)))

;**************************************
(defun winning.move (count p)
  (prog ()
        begin
        (cond ((or (memq count p1) (memq count p2))
               (setq count (iadd count 1)) 
               (go begin))
              ((> count 9) (return nil))
              ((check wins (cons count p)) (return count))
              (t (winning.move (iadd 1 count) p)))))

;**************************************
;This returns a randomly chosen position that has not
;already been chosen.

(defun random.choice ()
  (prog (temp)
        loop
        (setq temp (iadd 1 (random 9)))
        (if (or (memq temp p1) (memq temp p2))
            (go loop)  ;If that position is chosen, get another.
            temp)))  ;Otherwise output the position.

;**************************************
;This manages the human player's move.

(defun player2 ()
  (prog (choice)
        (fillrect '(-110 -201 10 -100) white)
        (moveto -200 0) 
        (drawstring "You")
        loop
        (setq choice (position))
        (if (or (memq choice p1) (memq choice p2))
            (go loop))
        (push choice p2)
        (filloval (car (last (assq choice places))) gray)))

;**************************************
;This gets a position from the mouse.

(defun position ()
  (prog (pt count)
        begin
        (if (not (button)) (go begin))
        (setq pt (getmouse))
        (if (not (pt.in.rect 
                   (car pt) (car (last pt)) 
                   '(-85 -85 85 85)))
            (go begin))
        
        (setq count 1)  ;incremented for a position number
        pointer
        (if (pt.in.rect (car pt) 
                        (car (last pt))
                        (car (last (nth (isub count 1) places))))
            (return count)
            (progn 
              (setq count (iadd count 1))
              (go pointer)))))

;**************************************
;PT.IN.RECT tests to see whether a
;specific X and Y coordiate lies within 
;a given boundary rectangle :RECT.
;RECT should be a list of [TOP LEFT BOTTOM
; RIGHT] coordinates.

(defun pt.in.rect (x y rect)
  (and (< x (nth 3 rect))
       (  x (nth 1 rect))
       (¾ y (nth 2 rect))
       (  y (nth 0 rect))
       t))  ;returns T if true, NIL otherwise

Next month will include an indepth description of MacScheme, the first installment of an ExperOps5 tutorial and a couple more Lisp functions.

 
AAPL
$106.86
Apple Inc.
-0.49
MSFT
$45.91
Microsoft Corpora
-0.72
GOOG
$549.55
Google Inc.
+0.22

MacTech Search:
Community Search:

Software Updates via MacUpdate

LibreOffice 4.3.3.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
VMware Fusion 7.0.1 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
OneNote 15.3.2 - Free digital notebook f...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more
Audio Hijack Pro 2.11.4 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Iridient Developer 3.0.0 beta 3 - Powerf...
Iridient Developer (was RAW Developer) is a powerful image conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more
TextWrangler 4.5.11 - Free general purpo...
TextWrangler is the powerful general purpose text editor, and Unix and server administrator's tool. Oh, and also, like the best things in life, it's free. TextWrangler is the "little brother" to... Read more
NeoFinder 6.6 - Catalog your external me...
NeoFinder (formerly CDFinder) rapidly organizes your data, either on external or internal disks, or any other volumes. It catalogs all your data, so you stay in control of your data archive or disk... Read more
Chromium 38.0.2125.111 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. FreeSMUG-Free OpenSource Mac User Group build is... Read more
Default Folder X 4.6.11 - Enhances Open...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
Mariner Write 3.9.3 - Light-weight and s...
Mariner Write is your Mac OS go-to word processing tool! Professional writer, educator or student, Write has all the functionality you need for that important letter, technical paper or research... Read more

Latest Forum Discussions

See All

Naailde the Witch Review
Naailde the Witch Review By Amy Solomon on October 30th, 2014 Our Rating: :: PITCH-PERFECT STORYTELLINGUniversal App - Designed for iPhone and iPad Marvelous storytelling, narration, and moving illustrations make this storybook... | Read more »
1st & Goal Review
1st & Goal Review By Andrew Fisher on October 30th, 2014 Our Rating: :: FOR THE D&D LOVING QBUniversal App - Designed for iPhone and iPad 1st & Goal is a board gamer’s football game, a football fan’s board game, and... | Read more »
French Developer Pated Unveils Seashine
French Developer Pated Unveils Seashine Posted by Ellis Spice on October 30th, 2014 [ permalink ] French one-man studio Pated has unveiled Seashine, “a poetic journey into the abyss.” Players take on the role of a jellyfish strugglin | Read more »
Agents of Storm: Tips, Tricks, and Strat...
Calling all agents: Would you like to see what we thought of this rather pretty base builder? Check out our Agents of Storm review! Have you downloaded Agents of Storm, been bowled over by the graphics, and aren’t quite sure what to do next? Never... | Read more »
Any.DO 2.0 Hopes to Help Manage Producti...
Any.DO 2.0 Hopes to Help Manage Productivity Posted by Ellis Spice on October 30th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Base Busters Review
Base Busters Review By Jennifer Allen on October 30th, 2014 Our Rating: :: FUN BUT RESTRICTED MIXUniversal App - Designed for iPhone and iPad Mixing up two forms of tower defense gaming and collectible cards, Base Busters is a fun... | Read more »
Sumptus - Personal Expense Tracker in Yo...
Sumptus - Personal Expense Tracker in Your Pocket 1.0 Device: iOS iPhone Category: Finance Price: $3.99, Version: 1.0 (iTunes) Description: Sumptus - a personal finance assistant in your pocket. It’s an ultimate expense tracker... | Read more »
Meat Factory (Games)
Meat Factory 0.1 Device: iOS Universal Category: Games Price: $.99, Version: 0.1 (iTunes) Description: Meat factory harks back to the old days of the game and watch. Easy to pick up and play, but hard to score big. With cute visuals... | Read more »
Medford Asylum: Paranormal Case - Hidden...
Medford Asylum: Paranormal Case - Hidden Object Adventure (Full) 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Uncover the mystery of Medford City asylum! | Read more »
Secret Files Sam Peters (Games)
Secret Files Sam Peters 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: [ After the successful iOS release of Secret Files Tunguska, the acclaimed point and click adventure Secret Files... | Read more »

Price Scanner via MacPrices.net

Apple now offering refurbished 2014 15-inch M...
The Apple Store is now offering Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Apple drops prices on refurbished 2013 Retina...
The Apple Store has dropped prices on 2013 Apple Certified Refurbished 13″ and 15″ Retina MacBook Pros, with Retina models now available starting at $999. Apple’s one-year warranty is standard, and... Read more
New 2.8GHz Mac mini on sale for $949, save $5...
Abt Electronics has the new 2.8GHz Mac mini in stock and on sale for $949.05 including free shipping. Their price is $50 off MSRP, and it’s the lowest price available for this model from any reseller... Read more
Sale! 3.7GHz Quad Core Mac Pro available for...
 B&H Photo has the 3.7GHz Quad Core Mac Pro on sale for $2649 including free shipping plus NY sales tax only. Their price is $350 off MSRP, and it’s the lowest price for this model from any... Read more
Mujjo Steps Up The Game With Refined Touchscr...
Netherlands based Mujjo have just launched their Refined Touchscreen Gloves, stepping up their game. The gloves feature a updated elegant design that takes these knitted gloves to the next level. A... Read more
Sale! Preorder the new 27-inch 5K iMac for $2...
 Abt Electronics has the new 27″ 3.5GHz 5K iMac on sale and available for preorder for $2374.05 including free shipping. Their price is $125 off MSRP, and it’s the lowest price available for this... Read more
Simplex Solutions Inc. Brings Secure Web Surf...
New York based Simplex Solutions Inc. has announced the release and immediate availability of Private Browser 1.0, its revolutionary new secure web browser developed for iPhone, iPad and iPod touch... Read more
Save up to $180 off MSRP with an Apple refurb...
The Apple Store has Apple Certified Refurbished 2014 MacBook Airs available for up to $180 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is free.... Read more
Apple refurbished 2013 MacBook Pros available...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more
What Post PC Era? – The Mac Bounces Back, Big...
Apple’s fiscal Q4 2014 was an all-time record quarter for Mac sales, with 5.5 million units shipped, representing nearly one million more sales (+21 percent, + 25 percent sequentially) than Apple... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple I...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
*Apple* Solutions Consultant (ASC) - Apple I...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
*Apple* Solutions Consultant (ASC) - Apple I...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
*Apple* Solutions Consultant - Apple Inc. (U...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
*Apple* Solutions Consultant - Apple Inc. (U...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.