开发者

Representing game board for connect 4 in prolog

开发者 https://www.devze.com 2023-01-25 10:05 出处:网络
I am trying to make an interactive, text-based connect4 game in SWI P开发者_开发知识库rolog, and I\'m a little stuck on how to start. What I don\'t understand is how to represent the game board, since

I am trying to make an interactive, text-based connect4 game in SWI P开发者_开发知识库rolog, 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 3x3, [[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 via select(cell(1,2,Value), L, Rem) to extract the Value of cell at position 1,2 from the list of cells, L, allowing you to manipulate it and create the full list again by creating a new cell/3 term and appending it to Rem.

I would advise against using the assert/retract mechanism in writing code to handle this problem; it's messy, unnecessary, and not conducive to writing easily understandable and 'debuggable' PROLOG code.


(I hope you are talking about this game).

You have a several choices.

You can have a list of lists for the whole field, like [[empty,empty,yellow,red,empty],[red,red,red,yellow,yellow],[red,red,red,red,red]].

Or you can assert/retract facts like

red(2, 4). red(1, 3). yellow(2, 2). red(3, 2).

The game is simple, so choose whatever matches your intuitive representation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号