1
+ import numpy as np
2
+
3
+
4
+ grid = np .full ((3 ,3 ), '-' )
5
+ cells = {'0' : (0 ,0 ), '1' : (0 ,1 ), '2' : (0 ,2 ),
6
+ '3' : (1 ,0 ), '4' : (1 ,1 ), '5' : (1 ,2 ),
7
+ '6' : (2 ,0 ), '7' : (2 ,1 ), '8' : (2 ,2 )}
8
+
9
+ diagonal_1 = [0 ,1 ,2 ], [0 ,1 ,2 ] # main diagonal
10
+ diagonal_2 = [0 ,1 ,2 ], [2 ,1 ,0 ] # reverse diagonal
11
+ ver_hor_lines = {'v1' : grid [:,0 ], 'v2' : grid [:,1 ], 'v3' : grid [:,2 ], # verticals
12
+ 'h1' : grid [0 ,:], 'h2' : grid [1 ,:], 'h3' : grid [2 ,:]} # horizontals
13
+
14
+ player = ''
15
+ turn = 1
16
+ free_spots = ['0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' ]
17
+ spot = ''
18
+
19
+ while True :
20
+ # printing the grid
21
+ for el in grid :
22
+ print (' ' .join (el .astype (str )))
23
+
24
+ # check if player won
25
+ if np .all (grid [diagonal_1 ] == player ) or np .all (grid [diagonal_2 ] == player ):
26
+ print (f"player { player .upper ()} , you won !" )
27
+ quit ()
28
+ for line in ver_hor_lines :
29
+ if np .all (ver_hor_lines [line ] == player ):
30
+ print (f"player { player .upper ()} , you won !" )
31
+ quit ()
32
+ print ('available positions: {}' .format (' ' .join (free_spots )))
33
+
34
+ # check if game ended as a tie
35
+ if not free_spots :
36
+ print ('END GAME: TIE' )
37
+ break
38
+
39
+ # update the player
40
+ if turn % 2 == 0 :
41
+ player = 'o'
42
+ else :
43
+ player = 'x'
44
+
45
+ # ask the input
46
+ spot = input ('player {}, enter a position: ' .format (player .upper ()))
47
+ # entering 'out' will end the game at anytime
48
+ if spot == 'out' :
49
+ quit ()
50
+ # check if input is valid
51
+ if spot in free_spots :
52
+ # update the grid
53
+ position = cells [spot ]
54
+ grid [position ] = player
55
+ free_spots .remove (spot )
56
+ turn += 1
57
+ else :
58
+ print ('not valid. Enter again.' )
59
+
60
+ print ()
0 commit comments