I'm trying to create a program in CommonLISP that creates a 4*4 table in which the player has a total of 16 pieces he can play and the goal is to reach 4 common traits between the pieces placed on the board, each piece has 4 traits, a color(white or black), a shape (square or round), a height(low or high) and a depth(empty or full) whether it be horizontal, vertigal or obliqual in order to win. After this, i wanted to apply searching algorithms such as BFS and DFS in order to examine the solution outcomes.
To do this, i've devided the program into 3 separate lisp files, one for the loading/GUI, one for the game puzzle and one where i will later incorporate the algorithms.
I have the Loading/GUI file done, but i'm uncertain as to how i should implement the game logic via code and would wish to get help in what would be the most efficient way of implementing this.
This is a test board that i've made, the first part of it being towards the board, and the second are the pieces of the board that are in reserve.
(defun test-board ()
"Return an test board"
'(
(
((white round high empty) 0 0 0)
(0 (black round high empty) 0 0)
(0 0 (white round low empty) 0)
(0 0 0 0)
)
(
( white round high full)
( white round low full)
( white square high empty)
( white square low empty)
( white square high full)
( white round low full)
( black round high full)
( black round low full)
( black round low empty)
( black square high full)
( black square high empty)
( black square low full)
( black square low empty)
)
)
)
How would i go about coding a function that allows me to make a play and identify if the game is over or not based on the traits being shared?
I was thinking of how to differently express you data, but then I remembered section "5.4 Defining Structure Types" of htdp2 book and thought that your starting point may actually work fine. In summary, defining a structure means defining three types of functions:
A constructor. This function takes as arguments the fields and creates an instance of the structure.
A selector per field that extracts the value of a field from an instance.
A structure predicate, which tells you whether an instance is of your structure type.
You've so far done step 1. Your function will return an instance. The first remark is, your function is returning a static list, and to my knowledge will return the same object each time you call it, i.e. lisp will create the object in memory statically (like a literal) when the function is defined and calling the function from anywhere anytime will return that same memory. That means you will only have one instance of that object everywhere. If you'd like a structure that can be instantiated each time you call the function, you would start with a (list ...) call instead of '((((white round...) in your function, but that's a bit more involved, and also your method may just be fine for your purpose. Let me show you what I mean with some code:
(defparameter tb1 (test-board))
(defparameter tb2 (test-board))
(eq tb1 tb2)
> T
(eq tb1 (test-board))
> T
(eq) call shows that they are exactly the same items in memory. That means changing an element through one variable / function call will change the same object. Here:
tb1
> ((((WHITE ROUND HIGH EMPTY) 0 0 0) (0 (BLACK ROUND HIGH EMPTY) 0 0)
(0 0 (WHITE ROUND LOW EMPTY) 0) (0 0 0 0))
...
(setf (caaaar tb1) 'black)
tb1
> ((((BLACK ROUND HIGH EMPTY) 0 0 0) (0 (BLACK ROUND HIGH EMPTY) 0 0)
(0 0 (WHITE ROUND LOW EMPTY) 0) (0 0 0 0))
...
(test-board)
> ((((BLACK ROUND HIGH EMPTY) 0 0 0) (0 (BLACK ROUND HIGH EMPTY) 0 0)
(0 0 (WHITE ROUND LOW EMPTY) 0) (0 0 0 0))
...
OK, now that we know some details of our structure, let's continue with the items 2 and 3 from the book. Given you're interested in 4 traits, you'd like selector functions for them given a piece. But we also need a selector for a piece given a test-board. So you should first write a function called (get-piece). You'll get a piece either from the board or the reserve, so maybe have two different get-piece functions, get-piece-from-board and get-piece-from-reserve.
(defun get-piece-from-board (position)
"Return a piece object from the position
e.g. Given a position '(0 1 0 0), would return '(black round high empty)
from the initial board."
...)
(defun get-first-from-reserve ()
"Return the first item in reserve."
...)
Since (test-board) always returns the same instance, we may skip item 3 / predicate for structure as we won't be comparing different test-boards.
Then you want selectors for traits:
(defun get-color (piece)
(first piece))
(defun get-shape (piece)
(second piece))
and so forth.
I won't get into details of writing the above functions, and let you practice. But here are some pointers to help you.
To get the board section, use (car tb1), or this is the same: (car (test-board)). And it's a good idea to put this down as a function:
(defun get-board ()
(car (test-board)))
And to get the reserve:
(defun get-reserve ()
(cadr (test-board)))
you may want to remove items from reserve or add them:
(defun remove-piece-from-reserve (piece)
"Remove piece from reserve."
(setf (get-reserve) (remove piece (get-reserve) :test #'equal))) ;; (remove ...) call will remove the item that's #'equal to "piece" and return a list without that item, then you (setf) that result back to the (get-reserve) position to save it.
You can add a piece with (push) function. I suggest a separate add-piece-to-reserve definition.
I'm hoping now you would be closer to write the functions to "make a play" and "identify if game is over".
Related
I'm taking an intro programming class. We use the student languages in DrRacket.
Problem: I would like to return a certain value at the end of a big-bang game (require 2htdp/universe)`.
Current Output: When the game ends, DrRacket returns my current worldstate, which is a list of structures that I use in the game.
Progress towards solution: It seems like stop-with may be able to help me, but I'm not sure how to use it.
TL;DR:
Problem: Game Ends --> Returns World State (List of Structures)
Want: Game Ends --> Return Other Value (Number)
Let me know if I can clarify in any way! Thanks!
EDIT: I think I found the solution. I use the expression that I usually call for my end? function and put it instead as a cond branch in my on-tick function. When that function is called in my on-tick function, then it changes the world-state to whatever I want to output. Then, in my end? function, I just check to see whether the worldstate is something different than it usually is.
Thanks for the help!
Solution:
; A Test Case (TC) is a (make-tc Number)
(define-struct tc [number ticks])
; number is a number used to test this problem
; TC -> Number
; Begins the main big-bang function; outputs the inverse of tick speed
; times the number of ticks elapsed when the game ends.
(define (main tick-speed)
( * (/ 1 tick-speed)
(tc-ticks (big-bang (make-tc 0 0)
[to-draw draw]
[on-tick check tick-speed]
[stop-when end? end-scene]))))
Answered in the original post:
; A Test Case (TC) is a (make-tc Number)
(define-struct tc [number ticks])
; number is a number used to test this problem
; TC -> Number
; Begins the main big-bang function; outputs the inverse of tick speed
; times the number of ticks elapsed when the game ends.
(define (main tick-speed)
( * (/ 1 tick-speed)
(tc-ticks (big-bang (make-tc 0 0)
[to-draw draw]
[on-tick check tick-speed]
[stop-when end? end-scene]))))
If I know the position of an element in a list in clisp, then how could I retrieve the element knowing its position. Is there any predefined function for it?
For lists only there is NTH:
CL-USER> (nth 2 '(1 2 3 4 5))
3
For SEQUENCES (vectors, strings, lists ...) there is ELT:
CL-USER> (elt '(1 2 3 4 5) 2)
3
If you really need a lot to access element by index, I'll advice you to consider using vectors (and access elements by aref) instead of lists, especially if you have logn sequences, because accessing element by index in lists may need to travel along all list to your element.
Of course, if you have small amount of data, you wan't feel any difference, but it looks good to use things right for me.
I depends on your lisp flavour. The best thing is to just write a 2 parameter function which returns a list-item. Parameter 1 item_index, param 2 the list, just recursively reduce index as you move through and return the 0th of 1st index. Note you need to decide if the car of a list is index 1 or index 0. Humans prefer one,computers 0.
I am reading a Gentle Introduction to Symbolic Computation and it asks this question. Basically, the previous content deals with making up bigger functions with small ones. (Like 2- will be made of two 1- (decrement operators for lisp))
So one of the questions is what are the two different ways to define a function HALF which returns one half of its input. I have been able to come up with the obvious one (dividing number by 2) but then get stuck. I was thinking of subtracting HALF of the number from itself to get half but then the first half also has to be calculated...(I don't think the author intended to introduce recursion so soon in the book, so I am most probably wrong).
So my question is what is the other way? And are there only two ways?
EDIT : Example HALF(5) gives 2.5
P.S - the book deals with teaching LISP of which I know nothing about but apparently has a specific bent towards using smaller blocks to build bigger ones, so please try to answer using that approach.
P.P.S - I found this so far, but it is on a completely different topic - How to define that float is half of the number?
Pdf of book available here - http://www.cs.cmu.edu/~dst/LispBook/book.pdf (ctrl+f "two different ways")
It's seems to be you are describing peano arithmetic. In practice it works the same way as doing computation with fluids using cups and buckets.
You add by taking cups from the source(s) to a target bucket until the source(s) is empty. Multiplication and division is just advanced adding and substraction. To halve you take from source to two buckets in alterations until the source is empty. Of course this will either do ceil or floor depending on what bucket you choose to use as answer.
(defun halve (x)
;; make an auxillary procedure to do the job
(labels ((loop (x even acc)
(if (zerop x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
;; use the auxillary procedure
(loop x nil 0)))
Originally i provided a Scheme version (since you just tagged lisp)
(define (halve x)
(let loop ((x x) (even #f) (acc 0))
(if (zero? x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
Edit: Okay, lets see if I can describe this step by step. I'll break the function into multiple lines also.
(defun half (n)
;Takes integer n, returns half of n
(+
(ash n -1) ;Line A
(if (= (mod n 2) 1) .5 0))) ;Line B
So this whole function is an addition problem. It is simply adding two numbers, but to calculate the values of those two numbers requires additional function calls within the "+" function.
Line A: This performs a bit-shift on n. The -1 tells the function to shift n to the right one bit. To explain this we'll have to look at bit strings.
Suppose we have the number 8, represented in binary. Then we shift it one to the right.
1000| --> 100|0
The vertical bar is the end of the number. When we shift one to the right, the rightmost bit pops off and is not part of the number, leaving us with 100. This is the binary for 4.
We get the same value, however if we perform the shift on nine:
1001| --> 100|1
Once, again we get the value 4. We can see from this example that bit-shifting truncates the value and we need some way to account for the lost .5 on odd numbers, which is where Line B comes in.
Line B: First this line tests to see if n is even or odd. It does this by using the modulus operation, which returns the remainder of a division problem. In our case, the function call is (mod n 2), which returns the remainder of n divided by 2. If n is even, this will return 0, if it is odd, it will return 1.
Something that might be tripping you up is the lisp "=" function. It takes a conditional as its first parameter. The next parameter is the value the "=" function returns if the conditional is true, and the final parameter is what to return if the conditional is false.
So, in this case, we test to see if (mod n 2) is equal to one, which means we are testing to see if n is odd. If it is odd, we add .5 to our value from Line A, if it is not odd, we add nothing (0) to our value from Line A.
I have to represent a board game using lisp. To do that i have to create a function that builds the board.
This function receives an integer that represents the number of sublist the original list as to have. each one of this sublists have a different size growing in 3*n proportion.
As an example ifthe function is called with the number 3, it will create a list with 3 sublists, the first with 3 position, the second with six and the third with 9.
Also, each of the positions need to be initialized with ยด*.
To do this i think i have to make a recursive call to make-list, but i can't seem to do that right. i'be tried to use the 'dotimes' cycle to do that, but i didn't have any sucess with that.
So far i have:
(defun faz-tabuleiro (n_aneis)
(make-list n_aneis :initial-element (...)
Wich creates the main list, but how can i represent the sublists inside with the right size?
Does this do what you want?
(defun make-table (n)
(loop :for i :from 1 :to n
:collect (make-list (* i 3) :initial-element "*")))
Map over a list of numbers being the length of the sublists. Use a function for this mapping which returns the right list initialized with the initial element.
Can someone please guide me or explain how to perform backtracking in LISP ? Any examples or links would be appreciated.
I did try to google , however none of them had simple example enough for me to understand.
Thanks
The typical way is to have non-mutable state passed down the call-stack, with helper functions taking the current state-returning a new state to "fake" mutation.
A possible (although rather suboptimal) sudoku-solver would then be:
;;; Use a list of 81 integers to represent a sudoku board,
;;; each number 1-9 represents itself, 0 represents a blank
(defun sudoku-solver (board)
(cond ((notany #'zerop board)
(if (sudoku-solved-p board)
board
nil))
(t (let ((positions (sudoku-all-blanks board)))
(loop for position in positions
do (loop for number in '(1 2 3 4 5 6 7 8 9)
do (let ((result (sudoku-solver
(sudoku-set board
position
number))))
(when result
(return-from sudoku-solver result)))))))))
This will automatically backtrack until a solution is found. I have skipped obscuring the demonstration with the support code that would turn it from a demonstration to actual working code.