I am trying to make an interactive, text-based connect4 game in SWI Prolog, and I’m a little stuck on how to start. What I don’t understand is how to represent the game board, since I don’t think I can have arrays, or variables that can be seen and modified by all rules.
Any insight as to how to start would be greatly appreciated!
An appropriate representation of a data structure amenable to your situation is often half the problem in PROLOG.
There are many ways of representing things in a grid like a 2-dim array in PROLOG, but I’d argue that the easiest are probably list-based, since there is a lot of inherent support for list structures:
1. List-of-lists. E.g., for a 3×3,
[[a,b,c],[d,e,f],[g,h,i]]. Your interpretation of this structure will be inherent in your code to traverse and manipulate it (i.e.,[a,b,c]can be a row, or a column, it’s up to you, just be consistent). To access an individual cell, you’d need to traverse the structure with a predicate that counts (or matches to) particular positions.2. List-of-terms. E.g.,
[cell(0,0,a), cell(0,1,b), ..., cell(2,2,i)]. This would allow you to pull out individual cells directly, such as viaselect(cell(1,2,Value), L, Rem)to extract theValueof cell at position1,2from the list of cells,L, allowing you to manipulate it and create the full list again by creating a newcell/3term and appending it toRem.I would advise against using the
assert/retractmechanism in writing code to handle this problem; it’s messy, unnecessary, and not conducive to writing easily understandable and ‘debuggable’ PROLOG code.