首页 > 解决方案 > Prolog中的猜数字游戏

问题描述

我正在尝试构建一个简单的程序,其中用户有 3 次尝试猜测一个数字,但存在编译错误,我不知道问题出在哪里。

actual_number(500).
actual_number(Num).
start:-
write('Enter your first guess'), nl,
read(Guess1),
Guess1 =\= Num -> write('Wrong you have 2 tries left'),
read(Guess2);
Guess1 == Num -> write('Correct'),!.
Guess2 =\= Num -> write('Wrong you have 1 try left'),
read(Guess3);
Guess2  == Num -> write('Correct'),!.
Guess3 =\= Num -> write('Wrong the number was 500'),!;
Guess3 == Num -> write('Correct').

标签: prolog

解决方案


我使用Swish来测试代码。与以下第一个代码剪切的主要区别在于以下版本更加结构化并且不使用剪切。由于您使用的是 If-the-else 指令,这些指令本身就使用了削减,因此不需要削减。请注意,;调用的析取 ( ) 与合取 ( ) 的优先级不同,。使用括号来定义析取的范围以及 if-then-else 必须为真才能触发的语句。

actual_number(500).

start:-
    actual_number(Num),
    write('Enter your first guess'), nl,
    read(Guess1),
    (   Guess1 == Num 
    ->  write('Correct')
    ;   write('Wrong you have 2 tries left'), nl,
        read(Guess2),
        (   Guess2 == Num 
            ->  write('Correct')
        ;   write('Wrong you have 1 try left'), nl,
            read(Guess3),
            (   Guess3 == Num 
            ->  write('Correct')
            ;   write('Wrong the number was '),
                write(Num)
            )
        )
    ).

第二种方法计算尝试的次数并且原则上相同,只是代码更加prolog-ish。

actual_number(500).

start:-
    write('Enter your first guess'), nl,
    start(3).

start(N):-
    N>0,
    actual_number(Num),
    read(Guess),
    (   Guess == Num
    ->  write('Correct')
    ;   Nnew is N-1,
        write('Wrong you have '),
        write(Nnew), 
        write(' tries left'), nl,
        start(Nnew)
    ).
    
start(0):-
    actual_number(Num),
    write('Wrong the number was '),
    write(Num).
    
    

推荐阅读