#!/usr/bin/mawk -f
BEGIN {
BC="\033[1;34m" # Board Color, default = light blue
print "\nmu-Connect4 (may 1999) \033[1mAndrea Manzini <linux@netbusiness.it>"
print "\033[0mYou have naughts, I have crosses. To move, type a number 1-7"
split("1:8:9:10",D,":")
split(" :\033[31mx:\033[32mo",A,":")
HEA="\n  1   2   3   4   5   6   7"
SEP="\n+---+---+---+---+---+---+---+\n"
ORS=""
for(i=1;i<=72;i++) B[i]=-9
for(i=11;i<=56;i+=9) { for(j=i;j<=i+6;j++) B[j]=0 } 
for(i=1;i<10;i++) Lst[i]=i+54
turn=int(rand()+0.5)+1
while(moves<42) { 
	refresh(); 
	if (turn==2) {
		do { k=prompt() } while(k==0)
	} else {
		k=cpumove()
		print "My move: " k " (Press RETURN to continue)"
		getline
	}
	k++; moves++; B[Lst[k]]=turn;
	for (i in D) { sq=Lst[k]; t=0
		while( B[sq+=D[i]] == turn ) t++;
		sq=Lst[k]
		while( B[sq-=D[i]] == turn ) t++;
		if (t>2) {
			refresh(); 
			if (turn==2) print "YOU WIN!\n"
			if (turn==1) print "YOU LOSE!\n"
			exit
		}
	}
	Lst[k]-=9; turn=3-turn
}
refresh();
print "\nIT'S A DRAW !!\n"
}

function prompt() {
i=0
print "Enter your move (1-7): "
getline i 
if (i<1) i=0
if (i>7) i=0 
if (Lst[i+1]<10) i=0
return i
}

function refresh()
{
print BC HEA SEP 
for(j=2;j<8;j++) {
	for(i=2;i<=8;i++) {
		k=j*9+i-9
		print "| " A[B[k]+1] BC " "; 
		}
	print "|"SEP
	}
print "\033[0m"
}

function cpumove()
{
Hi=-999
for(j=2;j<=8;j++) {
End=Lst[j] 
if (End!=j) {
	P=score(1); Q=score(2); if(Q>P) P=Q
	if(P==Hi && rand()>0.5 ) Mv=j 
	if(P>Hi) { Hi=P; Mv=j }
	}
}
return Mv-1
}

function score(Pl) {
sc=-Pl;
for(i in D) {
	t=-1; sq=End;
	do { sq+=D[i]; t++ } while(B[sq] == Pl)  
	f1=(B[sq]==0); sq=End;
	do { sq-=D[i]; t++ } while(B[sq] == Pl) 
	t--; sc+=(B[sq]==0)*f1*(3^t)+1000*(t>2);
	}
return sc;
}
