Code covered by the BSD License  

Highlights from
AI for a game called chomp

from AI for a game called chomp by abhilash harpale
this program uses the minimax algorithm for playing chomp.open the file create_tree for instrutions.

play(tree)
%Copywrite Abhilash Harpale (c) 2009.
%This function takes the solved tree as the input and plays the game.
%The cells are numbered along the rows with the top left most numbered 1.
%The user must enter the number of the cell he/she wants to play.

function play(tree)
choice=input('do you want to play first ?(0/1) ');
col=1;

if(choice==1)
    human=1;
    computer=2;
else
    human=2;
    computer=1;
end

while (tree(4,1)==0)
    col=1;
    player=tree(3,1);
    if (player==computer)
        node_scores=[];
        for i=1:size(tree,2)
            if(tree(1,i)==2)
                node_scores=[node_scores [tree(2,i);i]];
            end
        end
        if(player==1)
            my_move=max(node_scores(1,:));
        else
            my_move=min(node_scores(1,:));
        end
         [r c]=find(node_scores==my_move);
         %node_scores 
         rand('state',sum(100*clock));
         x=rand(size(c));
         [y ind]=sort(x);
         c=c(ind(1));
         my_move=tree(2,node_scores(2,c(1,1))-1);
         my_move
         col=node_scores(2,c(1,1));
         flag=1;
         i=col+1;
        if (tree(1,i)==-3)
            tree=tree(1:4,col);
        else
            i=col+2;
            while(flag~=0)
                 if(tree(1,i)==-1)
                     flag=flag+1;
                 end
                if(tree(1,i)==-3)
                     flag=flag-1;
                end
                 i=i+1;
            end
            tree=tree(1:4,col:i-1);
            tree=tree-[(tree(1,:)>0);zeros(3,size(tree,2))];
        end
    else
        choice=input('enter your move- ');
        for i=2:(size(tree,2)-1)
            if(tree(2,i)==choice && tree(1,i+1)==2)
                col=i+1;
                break;
            end
        end
        flag=1;
        i=col+1;
        if (tree(1,i)==-3)
            tree=tree(1:4,col);
        else
            i=col+2;
            while(flag~=0)
                 if(tree(1,i)==-1)
                     flag=flag+1;
                 end
                if(tree(1,i)==-3)
                     flag=flag-1;
                end
                 i=i+1;
            end
            tree=tree(1:4,col:i-1);
            tree=tree-[(tree(1,:)>0);zeros(3,size(tree,2))];
        end
    end
end

if(tree(2,1)==-1 && computer==2)
    disp('computer wins!!');
elseif(tree(2,1)==-1 && human==2)
    disp('you win!!');
elseif(tree(2,1)==1 && computer==1)
    disp('computer wins!!');
elseif(tree(2,1)==1 && human==1)
    disp('you win!!');
else
    disp('it is a draw');
end
end

    
        
             

Contact us at files@mathworks.com