-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython1.py
157 lines (84 loc) · 2.76 KB
/
python1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
from random import randrange
def jogo_da_velha(tabuleiro):
print("+-------" * 3, "+", sep="")
for linha in range(3):
print("| " * 3, "|", sep="")
for coluna in range(3):
print("| " + str(tabuleiro[linha][coluna]) + " ", end="")
print("|")
print("| " * 3, "|", sep="")
print("+-------" * 3, "+", sep="")
def fazer_jogada(tabuleiro):
ok = False
while not ok:
jogada = input("Digite sua jogada: ")
ok = len(jogada) == 1 and jogada >= '1' and jogada <= '9'
if not ok:
print("Jogada inválida – repita sua entrada!")
continue
jogada = int(jogada) - 1
linha = jogada // 3
coluna = jogada % 3
sinal = tabuleiro[linha][coluna]
ok = sinal not in ['O', 'X']
if not ok:
print("Campo já ocupado – repita sua entrada!")
continue
tabuleiro[linha][coluna] = 'O'
def listar_campos_livres(tabuleiro):
livres = []
for linha in range(3):
for coluna in range(3):
if tabuleiro[linha][coluna] not in ['O', 'X']:
livres.append((linha, coluna))
return livres
def vitoria_por(tabuleiro, sgn):
if sgn == "X":
quem = 'eu'
elif sgn == "O":
quem = 'você'
else:
quem = None
cruzada1 = cruzada2 = True
for rc in range(3):
if tabuleiro[rc][0] == sgn and tabuleiro[rc][1] == sgn and tabuleiro[rc][2] == sgn:
return quem
if tabuleiro[0][rc] == sgn and tabuleiro[1][rc] == sgn and tabuleiro[2][rc] == sgn:
return quem
if tabuleiro[rc][rc] != sgn:
cruzada1 = False
if tabuleiro[2 - rc][2 - rc] != sgn:
cruzada2 = False
if cruzada1 or cruzada2:
return quem
return None
def jogar_computador(tabuleiro):
livres = listar_campos_livres(tabuleiro)
cnt = len(livres)
if cnt > 0:
this = randrange(cnt)
linha, coluna = livres[this]
tabuleiro[linha][coluna] = 'X'
tabuleiro = [[3 * j + i + 1 for i in range(3)] for j in range(3)]
tabuleiro[1][1] = 'X'
livres = listar_campos_livres(tabuleiro)
turno_humano = True
while len(livres):
jogo_da_velha(tabuleiro)
if turno_humano:
fazer_jogada(tabuleiro)
vitorioso = vitoria_por(tabuleiro, 'O')
else:
jogar_computador(tabuleiro)
vitorioso = vitoria_por(tabuleiro, 'X')
if vitorioso is not None:
break
turno_humano = not turno_humano
livres = listar_campos_livres(tabuleiro)
jogo_da_velha(tabuleiro)
if vitorioso == 'você':
print("Você ganhou!")
elif vitorioso == 'eu':
print("Eu ganhei!")
else:
print("Empate!")