#!perl -w use strict; my @table = (0, 0, 0, 0, 0, 0, 0, 0, 0); print "\n\t\ttris by babel\n\n"; for(my $i=0;; $i++) { &showTable; &getMove (1); if(&winner(1)){ print "\ngiocatore 1 vince la partita\n\n"; my $num2 = ; exit; } if($i==4){last} &bestMove (-1); if(&winner(-1)){ print "\ncpu vince la partita\n\n"; my $num2 = ; exit; } } &showTable; print"\n\npari"; my $num2 = ; sub bestMove { my $bestValue=-2000; my $bestMove; my $tempValue; for (my $i=0; $i<9; $i++) { if ($table[$i]!=0){ next; } $table[$i]=$_[0]; $tempValue = -&best(-$_[0]); $table[$i]=0; if ($tempValue>$bestValue){ $bestMove=$i; $bestValue=$tempValue; } } print "\ncpu move to $bestMove\n"; $table[$bestMove]=$_[0]; } sub best { my $bestValue=-1000; my $tempValue; if (&winner(-$_[0])){ return -1000; } for (my $i=0; $i<9; $i++) { if ($table[$i]!=0){ next; } $table[$i]=$_[0]; $tempValue = -&best(-$_[0]); $table[$i]=0; if ($tempValue>$bestValue) { $bestValue=$tempValue; } } return $bestValue/2; } sub winner { if (($table[0]==$_[0] && $table[1] ==$_[0] && $table[2] == $_[0]) || ($table[3]==$_[0] && $table[4] ==$_[0] && $table[5] == $_[0]) || ($table[6]==$_[0] && $table[7] ==$_[0] && $table[8] == $_[0]) || ($table[0]==$_[0] && $table[3] ==$_[0] && $table[6] == $_[0]) || ($table[1]==$_[0] && $table[4] ==$_[0] && $table[7] == $_[0]) || ($table[2]==$_[0] && $table[5] ==$_[0] && $table[8] == $_[0]) || ($table[0]==$_[0] && $table[4] ==$_[0] && $table[8] == $_[0]) || ($table[2]==$_[0] && $table[4] ==$_[0] && $table[6] == $_[0])) {return 1} return 0; } sub showTable { my @map; for(my $i=0 ; $i<9 ; $i+=1){ $map[$i] = $table[$i]==0? ' ':($table[$i]==1? 'x':'o') ; } print "\n\t$map[6]|$map[7]|$map[8]"; print "\n\t-+-+-"; print "\n\t$map[3]|$map[4]|$map[5]"; print "\n\t-+-+-"; print "\n\t$map[0]|$map[1]|$map[2]"; } sub getMove { print"\nplayer $_[0]: what do you want to move? (1..9)\n\t"; my $move = ; $move-=1; if($table[$move]!=0){ die "\nyou are stupid!"; }else{ $table[$move]=$_[0]; } }