实现计数器序言 [英] Implement counter prolog

查看:55
本文介绍了实现计数器序言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PROLOG 中开发一个棋盘游戏,为了让用户更享受界面,我决定添加一个坐标为 (0->4) 的网格,如下所示:

I'm developing a board game in PROLOG and in order to make the interface more enjoyable for the user, I decided to add a grid with the coordinates (0->4) as shown below:

    0 1 2 3 4
    ---------
0 | x x x x x
1 | x o x o o
2 | o x o x x
3 | x x o o o
4 | o x x x o

在开发了一些代码之后,我遇到了一个关于垂直坐标计数器的问题.谓词在我实现计数器Index is Index + 1后立即停止,如下所示:

After developing some code, I came across with an issue regarding the counter for the vertical coordinates. The predicate stops right after I implement the counter Index is Index + 1, as shown below:

printGrid :- %Only prints the horizontal grid
        write('\t'), write(0), write('   '), write(1), write('   '), write(2), write('   '), write(3), write('   '), write(4), nl,
        write('\t'), write('------------------'), nl.     

printBoard([Head|Tail]) :-
        Index = 0,
        Index is Index + 1,
        % STOPS HERE ------------
        write('    '), write(Index), write('  |'), write(' '),
        printRow(Head),
        printBoard(Tail).
printBoard([]).

printRow([Head|Tail]) :-
        write(Head),
        write('  '),
        printRow(Tail).
printRow([]) :- nl.

我知道每次调用递归时计数器都会重置为 0,因此我真的不知道如何将索引设置为 0 一次然后从那里开始.有关如何解决这两个问题的任何提示?

I'm aware the counter will reset to 0 every time recursion is called, thus I don't really know how to set the Index to 0 just about once and go from there. Any tips on how to solve both of the issues?

推荐答案

我检查了@Otrebor 提供的链接,并想出了一个很好的解决方案.我忘记了绑定时无法更改变量的小"细节,因此我添加了一个额外的.这是它的外观:

I examined the link which @Otrebor provided and I came up with a fine solution. I forgot the "little" detail that when bound, a variable can't be changed, thus I added an extra one. Here's how it looks:

printBoard([], _).
printBoard([Head|Tail], Counter) :-
        Index is Counter + 1,
        write('    '), write(Index), write('  |'), write(' '),
        printRow(Head),
        printBoard(Tail, Index).

main :- printBoard(Board, 0).

这篇关于实现计数器序言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆