Python井字游戏

 1 import sys
 2 
 3 def print_board():
 4     for i in range(3):
 5         for j in range(3):
 6             print map[2 - i][j],
 7             if j != 2:
 8                 print '|',
 9         print ''
10 
11 def check_done():
12     for i in range(3):
13         if map[i][0] == map[i][1] == map[i][2] != ' ' or map[0][i] == map[1][i] == map[2][i] != ' ':
14             print turn, "Won!!!"
15             return True
16 
17     if map[0][0] == map[1][1] == map[2][2] != ' ' or map[0][2] == map[1][1] == map[2][0] != ' ':
18         print turn, "Won!!!"
19         return True
20     
21     if ' ' not in map[0] and ' ' not in map[1] and ' ' not in map[2]:
22         print "Draw"
23         return True
24 
25     return False
26 
27 turn = 'X'
28 done = False
29 map = [[' ', ' ', ' '],
30         [' ', ' ', ' '],
31         [' ', ' ', ' ']]
32 print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
33 print "7|8|9"
34 print "4|5|6"
35 print "1|2|3"
36 print_board()
37 while done != True:
38     print turn + "'s turn"
39     try:
40         pos = input("Select: ")
41         if 1 <= pos <= 9:
42             X = (pos - 1) / 3
43             Y = (pos - 1) % 3
44             if map[X][Y] == ' ':
45                 map[X][Y] = turn
46                 print_board()
47                 done = check_done()
48                 if done == False:
49                     if turn == 'X':
50                         turn = 'O'
51                     else:
52                         turn = 'X'
53     except:
54         print "You need to add a numeric value"
原文地址:https://www.cnblogs.com/findingsea/p/3293063.html