-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
274 lines (209 loc) · 6.73 KB
/
main.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
from random import randint
class BoardException(Exception):
pass
class BoardOutException(BoardException):
def __str__(self):
return "Вы попытались выстрелить за границу доски"
class BoardUsedException(BoardException):
def __str__(self):
return "Вы уже выстрелили в эту клетку"
class BoardWrongShipException(BoardException):
pass
class Dot:
def __init__(self, x, y):
self.x = x
self.y = y
def _eq_(self, other):
return self.x == other.x and self.y == other.y
class Ship:
def __init__(self, bow, l, o):
self.bow = bow
self.l = l
self.o = o
self.lives = l
@property
def dots(self):
ship_dots = []
for i in range(self.l):
cur_x = self.bow.x
cur_y = self.bow.y
if self.o == 0:
cur_x += i
elif self.o == 1:
cur_y += i
ship_dots.append(Dot(cur_x, cur_y))
return ship_dots
def shooten(self, shot):
return shot in self.dots
class Board:
def __init__(self, hid = False, size = 6):
self.size = size
self.hid = hid
self.count = 0
self.field = [ ["O"]*size for _ in range(size) ]
self.busy = []
self.ships = []
def get_size(self):
return self.size
def set_size(self, size):
self.size = size
def add_ship(self, ship):
for i in ship.dots:
if self.out(i) or i in self.busy:
raise BoardWrongShipException()
for i in ship.dots:
self.field[i.x][i.y] = "■"
self.busy.append(i)
self.ships.append(ship)
self.contour(ship)
def contour(self, ship, verb=False):
near = [
(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 0), (0, 1),
(1, -1), (1, 0), (1, 1)
]
for i in ship.dots:
for ix, iy in near:
cur = Dot(i.x + ix, i.x + iy)
if not (self.out(cur)) and cur not in self.busy:
if verb:
self.field[cur.x][cur.y] = "."
self.busy.append(cur)
def __str__(self):
res = ""
res += " | 1 | 2 | 3 | 4 | 5 | 6 |"
for i, row in enumerate(self.field):
res += f"\n{i + 1} | " + " | ".join(row) + " |"
if self.hid:
res = res.replace("■", "O")
return res
def out(self, dot1):
return not ((0 <= dot1.x < self.size) and (0 <= dot1.y < self.size))
def shot(self, dot2):
if self.out(dot2):
raise BoardOutException()
if dot2 in self.busy:
raise BoardUsedException()
self.busy.append(dot2)
for ship in self.ships:
if dot2 in ship.dots:
ship.lives -= 1
self.field[dot2.get_x()][dot2.get_y()] = "X"
if ship.lives == 0:
self.count += 1
self.contour(ship, verb = True)
print("Корабль уничтожен!")
return False
else:
print("Корабль ранен!")
return True
self.field[dot2.x][dot2.y] = "."
print("Мимо!")
return False
def begin(self):
self.busy = []
class Player:
def __init__(self, board, enemy):
self.board = board
self.enemy = enemy
def get_board(self):
return self.board
def ask(self):
raise NotImplementedError()
def move(self):
while True:
try:
target = self.ask()
repeat = self.enemy.shot(target)
return repeat
except BoardException as e:
print(e)
class Ai(Player):
def ask(self):
dot1 = Dot(randint(0, 5), randint(0, 5))
print(f"Ход компьютера: {dot1.x + 1} {dot1.y + 1}")
return dot1
class User(Player):
def ask(self):
while True:
cords = input("Ваш ход: ").split()
if len(cords) != 2:
print(" Введите 2 координаты! ")
continue
x, y = cords
if not (x.isdigit()) or not (y.isdigit()):
print(" Введите числа! ")
continue
x, y = int(x), int(y)
return Dot(x - 1, y - 1)
class Game:
def __init__(self, size=6):
self.size = size
pl = self.random_board()
co = self.random_board()
co.hid = True
self.ai = Ai(co, pl)
self.us = User(pl, co)
def random_board(self):
board = None
while board is None:
board = self.random_place()
return board
def random_place(self):
lens = [3, 2, 2, 1, 1, 1, 1]
board = Board()
attempts = 0
for l in lens:
while True:
attempts += 1
if attempts > 2000:
return None
ship = Ship(Dot(randint(0, self.size), randint(0, self.size)), l, randint(0, 1))
try:
board.add_ship(ship)
break
except BoardWrongShipException:
pass
board.begin()
return board
def greet(self):
print("Приветсвуем вас")
print("в игре")
print("морской бой")
print("-------------------")
print(" формат ввода: x y ")
print(" x - номер строки")
print(" y - номер столбца")
def loop(self):
num = 0
while True:
print("-" * 20)
print("Доска пользователя:")
print(self.us.board)
print("-" * 20)
print("Доска компьютера:")
print(self.ai.board)
if num % 2 == 0:
print("-" * 20)
print("Ходит пользователь!")
repeat = self.us.move()
else:
print("-" * 20)
print("Ходит компьютер!")
repeat = self.ai.move()
if repeat:
num -= 1
if self.ai.board.count == 7:
print("-" * 20)
print("Пользователь выиграл!")
break
if self.us.board.count == 7:
print("-" * 20)
print("Компьютер выиграл!")
break
num += 1
def start(self):
self.greet()
self.loop()
g = Game()
g.start()