DIM B(9), PW(8), ST(3)

LABEL Help
? "TIC-TAC-TOE"
? "THE MOVE POSITIONS ARE:"
?
? "1 2 3"
? "4 5 6"
? "7 8 9"

'===================
LABEL RESTART
FOR I=1 TO 9
	B(I)=0 
NEXT
?
? "YOU WILL BE 'X', I WILL BE 'O'" 
? "TYPE 0 IF YOU WANT ME TO GO FIRST"; 
INPUT sel
WINNER=0
IF sel=0 THEN PLAYER=1 ELSE PLAYER=-1
WHILE 1
	IF PLAYER=-1 
		GOSUB DISPLAY
		GOSUB USER
	ELSE
		GOSUB COMPUTER
	FI
	GOSUB CHECK
	PLAYER=-PLAYER
	IF WINNER THEN 1000
WEND

1000 ' EXIT LOOP
? 
GOSUB DISPLAY
?
IF WINNER=-1
	? "YOU WIN!"
ELIF WINNER=1
	? "I WIN!"
ELSE
	? "TIE!"
FI
PRINT
INPUT "TRY AGAIN (IF SO TYPE 0)";sel
PRINT
IF sel=0 THEN GOTO RESTART
END

'===================
LABEL USER
REPEAT 
	REPEAT
		PRINT
		INPUT "YOUR MOVE";P
	UNTIL NOT(P<1 OR P>9)
UNTIL B(P)=0
B(P)=PLAYER
RETURN

'===================
LABEL COMPUTER
PLAYER=1
GOSUB Check

' WINNER MOVE
FOR I=1 TO 8
	IF PW(I)=2
		GOSUB SELPOS
		? "CPU: ATT ";P
		GOTO 2000
	FI
NEXT

' DEFENCE MOVE
FOR I=1 TO 8
	IF PW(I)=-2
		GOSUB SELPOS
		? "CPU: DEF ";P
		GOTO 2000
	FI
NEXT

' SIMPLE MOVE
IF B(5)=0
	P=5
ELSE
	FOR I=1 TO 9
		IF B(I)=0
			P=I
			? "CPU: ANY ";P
			GOTO 2000
		FI
	NEXT
FI

2000
B(P)=PLAYER
RETURN

'===================
LABEL SELPOS
IF I < 4
	ST(1)=(I-1)*3+1:ST(2)=(I-1)*3+2:ST(3)=(I-1)*3+3
ELIF I < 7
	ST(1)=(I-4):ST(2)=(I-4)+3:ST(3)=(I-4)+6
ELIF I=7
	ST(1)=1:ST(2)=5:ST(3)=9
ELSE
	ST(1)=3:ST(2)=5:ST(3)=7
FI

IF B(ST(1))=0
	P=ST(1)
ELIF B(ST(2))=0
	P=ST(2)
ELSE
	P=ST(3)
FI
RETURN

'===================
LABEL Check
FOR I=1 TO 3
	PW(I)=B((I-1)*3+1)+B((I-1)*3+2)+B((I-1)*3+3)
	PW(I+4)=B(I)+B(I+3)+B(I+6)
NEXT
PW(7)=B(1)+B(5)+B(9)
PW(8)=B(3)+B(5)+B(7)
FOR I=1 TO 8
	IF PW(I)=-3 THEN WINNER=-1
	IF PW(I)= 3 THEN WINNER=1
NEXT

CNT=0
FOR I=1 TO 9
	IF B(I) THEN CNT=CNT+1
NEXT
IF CNT=9 THEN WINNER=999
RETURN 

'===================
LABEL DISPLAY
PRINT
FOR N=1 TO 9 STEP 3
	FOR O= 0 TO 2
		IF B(A(O+N))=0
			PRINT "- ";
		ELIF B(A(O+N))=1
			PRINT "O ";
		ELSE
			PRINT "X ";
		FI
	NEXT
	PRINT
NEXT
RETURN


