я учусь коммитить

This commit is contained in:
vitalii Malcov 2024-04-29 18:51:57 +02:00
parent 71ce427037
commit 21bae3e283
13 changed files with 149 additions and 334 deletions

View File

@ -1 +0,0 @@
main (4).py

View File

@ -0,0 +1,7 @@
from enum import Enum
class ShipDirection(Enum):
VERTICAL = 'VERTICAL'
HORIZONTAL = 'HORIZONTAL'
UNKNOWN = 'UNKNOWN'

View File

@ -1,9 +1,11 @@
from ShootResult import ShootResult
from ShipDirection import ShipDirection
from ShipMode import ShipMode
class ShipField:
def __init__(self):
self.field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
@ -15,10 +17,11 @@ class ShipField:
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.ships = [4, 3, 2, 2, 2, 1, 1, 1, 1]
self.field_size = 10
self.field_mode = 0
self.field_mode = ShipMode.PUT
self.ship_size = 4
self.ship_direction = 0
self.ship_direction = ShipDirection.VERTICAL
def __getitem__(self, item):
if item is None:
@ -27,36 +30,53 @@ class ShipField:
if type(item) is not int and item.isnumeric():
item = int(item)
if type(item) is int and 0 <= item < len(self.field):
if type(item) is int and 0 <= item <= len(self.field):
return self.field[item]
return None
def action(self, row,col):
if self.field_mode == 0:
if self.check_possible(row, col):
self.set_ship(row, col)
def action(self, row, col):
self.clear_marker()
elif self.field_mode == 1:
if self.field_mode == ShipMode.PUT:
if self.check_ship(row, col):
self.get_ship(row, col)
elif self.field_size in self.ships and self.check_possible(row, col):
self.set_ship(row, col)
elif self.field_mode == ShipMode.SHOOT:
self.shoot(row, col)
def target(self, row, col):
if self.field_mode == 0:
self.clear_market()
self.clear_marker()
if self.field_mode == ShipMode.PUT:
if self.check_possible(row, col):
if self.ship_direction == 0:
if self.ship_direction == ShipDirection.VERTICAL:
for r in range(row, row + self.ship_size):
self.field[r * self.field_size + col] = 'p'
if self.ship_size in self.ships:
self.field[r * self.field_size + col] = 'p'
else:
self.field[r * self.field_size + col] = 'r'
if self.ship_direction == 1:
if self.ship_direction == ShipDirection.HORIZONTAL:
for c in range(col, col + self.ship_size):
self.field[row * self.field_size + c] = 'p'
if self.field_size in self.ships:
self.field[row * self.field_size + c] = 'p'
else:
self.field[row * self.field_size + c] = 'r'
def clear_market(self):
else:
self.field[row * self.field_size + col] = '+'
def clear_marker(self):
for i in range(0, len(self.field)):
if self.field[i] == 'p':
self.field = ''
if self.field[i] == 'p' or self.field[i] == 'r':
self.field[i] = ''
if '+' in self.field[i]:
self.field[i] = self.field[i].replace('+', '')
def set_ship(self, row, col):
if row < 0 or row > self.field_size:
@ -64,13 +84,13 @@ class ShipField:
if col < 0 or col > self.field_size:
return
index = row * self.field_size + col
if self.ship_direction == 0:
if self.ship_direction == ShipDirection.VERTICAL:
if self.field_size - row < self.ship_size:
return
for r in range(row, row + self.ship_size):
index = r * self.field_size + col
self.field[index] = "1"
if self.ship_direction == 1:
if self.ship_direction == ShipDirection.HORIZONTAL:
if self.field_size - col < self.ship_size:
return
for c in range(col, col + self.ship_size):
@ -93,14 +113,14 @@ class ShipField:
return ShootResult.UNDEFINED
def check_possible(self, row, col, ship_direction):
if ship_direction == 0:
if ship_direction == ShipDirection.VERTICAL:
if self.field_size - row >= self.ship_size:
for r in range(row, row + self.ship_size):
if not self.check_blocked(self.field, r, col):
return False
return True
if ship_direction == 1:
if ship_direction == ShipDirection.HORIZONTAL:
if self.field_size - col >= self.ship_size:
for c in range(col, col + self.ship_size):
if not self.check_blocked(self.field, row, c):
@ -118,39 +138,46 @@ class ShipField:
return False
return True
def set_ship_size(self, value):
if value is None:
return
if type(value) is str and value.isnumeric():
value = int(value)
if type(value) is int and 1 <= value <= 4:
self.ship_size = value
if value.isnumeric():
nummer = int(value)
if 1 <= nummer <= 4:
self.ship_size = nummer
def set_ship_direction(self, value):
if value is None:
return
if value != ShipDirection.UNKNOWN:
self.ships_directin = value
if type(value) is str and value.isnumeric():
value = int(value)
if type(value) is int and 0 <= value <= 1:
self.ship_direction = value
def toggle_ship_direction(self):
if self.ship_direction == ShipDirection.VERTICAL:
self.ship_direction = ShipDirection.HORIZONTAL
else:
self.ship_direction = ShipDirection.VERTICAL
def toggle_field_mode(self):
if self.field_mode == 1:
self.field_mode = 0
if self.field_mode == ShipMode.PUT:
self.field_mode = ShipMode.SHOOT
else:
self.field_mode = 0
self.field_mode = ShipMode.PUT
def print_field(self):
print(self.ships)
for r in range(0, self.field_size):
blocked_string = ""
ship_string = ""
blocked_string = ''
ship_string = ''
for c in range(0, self.field_size):
blocked_string += str(self.check_blocked(self, r, c))[0] + ", "
blocked_string += str(self.check_blocked(r, c))[0] + ', '
ship_string += self.field[r * self.field_size + c] + ', '
print(blocked_string[:-2] + ' ' + ship_string[:-2])
print("********************************************************************")
print(ship_string[: -2])
print('********************************************************')
@staticmethod
def convert_to_json(obj):
if isinstance(obj, ShipField):
result = obj.__dict__
result['field_mode'] = obj.field_mode.value
result['ship_direction'] = obj.ship_direction.value
return result

View File

@ -0,0 +1,6 @@
from enum import Enum
class ShipMode(Enum):
PUT = 'PUT'
SHOOT = 'SHOOT'

View File

@ -1,5 +1,6 @@
from enum import Enum
class ShootResult(Enum):
EMPTY = "EMPTY"
DAMAGED = "DAMAGED"

View File

@ -0,0 +1,8 @@
{
'my_field': {
'field': [],
'ships': [],
'field_mode': 'PUT'
}
}

View File

@ -1,100 +0,0 @@
from tkinter import *
from enum import Enum
field_size = 10
empty_field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# set_ship(1, 1, 4, 1)
step1_field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', '1', '1', '1', '1', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# set_ship(0, 5, 3, 0)
step2_field = [' ', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
my_field = list(empty_field)
enemy_field = list(empty_field)
class ShootResult(Enum):
Enum = 0
Damaged = '\\'
Killed = X
Underfined = 'undefined'
def set_ship(field, row, col, size, direction):
if row < 0 or row > field_size - 1:
return
if col < 0 or col > field_size - 1:
return
if direction == 0:
if row + size > field_size - 1:
return
for r in range(row, row + size):
index = r * field_size + col
field[index] = '1'
if direction == 1:
if col + size > field_size - 1:
return
for c in range(col, col + size):
index = c * field_size + row
field[index] = '1'
def draw_field(field):
for r in range(0, field_size):
for c in range(0, field_size):
bg = 'white'
if field[index] == '1':
bg = 'ping'
elif field[index] == '\\':
bg = 'red'
elif field[index] == '0':
bg = 'black'
btn.configupe(bg=bg)
def button_action(field, row, col):
shoot(field, row, col)
colorize(field)
window = Tk()
window.title("Ship Craft!")
window.geometry('800x400')
set_ship(my_field, 1, 1, 4, 1)
draw_field(field_size)
window.mainloop()

View File

@ -1,3 +1,4 @@
import json
from tkinter import *
from ShipField import ShipField
@ -7,8 +8,6 @@ enemy_field = ShipField()
active_field = my_field
# 1. Определите перечисление (Enum) ShootResult со следующими значениями:
# EMPTY (мимо), DAMAGED (ранен), KILLED (убит), UNDEFINED (действие не определено)
def draw_field(window, field, col_offset):
buttons = []
@ -36,6 +35,10 @@ def colorize(field, buttons):
bg = 'black'
if field.field[i] == "p":
bg = 'blue'
if '+' in field[i]:
bg = 'orange'
if 'r' in field[i]:
bg = 'red'
buttons[i].configure(bg=bg)
@ -43,7 +46,7 @@ def keypress_handler(e):
global active_field
if e.keysym.isnumeric():
active_field.set_ship_size(e.keysym)
active_field.set_ship_size(int(e.keysym))
else:
if e.keysym == 'm':
@ -60,39 +63,42 @@ def left_button_click(buttons, row, col):
def right_button_click(d):
global active_field
active_field.toggle_field_direction()
active_field.toggle_field_mode()
def button_enter(buttons, row, col):
global active_field
if buttons == my_buttons:
active_field = my_field
enemy_field.clear_marker()
my_field.target(row, col)
elif buttons == enemy_buttons:
active_field = enemy_field
my_buttons.clear_marker()
my_field.clear_marker()
enemy_field.target(row, col)
colorize(my_field, my_buttons)
colorize(enemy_field, buttons)
def savebutton_click(event):
with open('test.json', 'w') as f:
json.dump(f, default=ShipField.convert_to_json)
window = Tk()
window.title("Ship Craft!")
window.geometry('940x410')
window.bind_all('<KeyPress>', keypress_handler)
set_ship(my_field, 1, 1, 4, 1)
set_ship(my_field,0, 6, 3, 0)
set_ship(my_field, 7, 3, 1, 0)
my_buttons = draw_field(window, my_field, 0)
enemy_buttons = draw_field(window, enemy_field, 11)
print(len(my_buttons))
print(len(enemy_buttons))
lbl = Label(window, text='', width=5, height=2)
lbl.grid(column=10, row=0)
savebutton = Button(window, text='Save', width=20, height=2)
savebutton.bind('<Button-1>', savebutton_click)
savebutton.grid(column=0, row=11, columnspan=4)
window.mainloop()

View File

@ -1,179 +0,0 @@
from tkinter import *
from tkinter import messagebox
import time
import random
tk = Tk()
app_running = True
size_canvas_x = 600
size_canvas_y = 600
s_x = s_y = 12 # размер игрового поля
step_x = size_canvas_x // s_x # шаг по горизонтали
step_y = size_canvas_y // s_y # шаг по вертикали
size_canvas_x = step_x * s_x
size_canvas_y = step_y * s_y
menu_x = 250
ships = s_x // 2 # определяем максимальное кол-во кораблей
ships_len1 = s_x // 3 # длина первого типа корабля
ships_len2 = s_x // 4 # длина второго типа корабля
ships_len3 = s_x // 6 # длина третьего типа корабля
ships_len4 = s_x // 12 # длина четвертого типа корабля
enemy_ships = [[0 for i in range(s_x + 1)] for i in range(s_y + 1)]
list_ids = [] # список объектов canvas
# print(enemy_ships)
def on_closing():
global app_running
if messagebox.askokcancel("Выход из игры", "Хотите выйти из игры?"):
app_running = False
tk.destroy()
tk.protocol("WM_DELETE_WINDOW", on_closing)
tk.title("Игра Морской Бой")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=size_canvas_x + menu_x, height=size_canvas_y, bd=0, highlightthickness=0)
canvas.create_rectangle(0, 0, size_canvas_x, size_canvas_y, fill="white")
canvas.pack()
tk.update()
def draw_table():
for i in range(0, s_x + 1):
canvas.create_line(step_x * i, 0, step_x * i, size_canvas_y)
for i in range(0, s_y + 1):
canvas.create_line(0, step_y * i, size_canvas_x, step_y * i)
draw_table()
def button_show_enemy():
for i in range(0, s_x):
for j in range(0, s_y):
if enemy_ships[j][i] > 0:
_id = canvas.create_rectangle(i * step_x, j * step_y, i * step_x + step_x, j * step_y + step_y,
fill="red")
list_ids.append(_id)
def button_begin_again():
global list_ids
for el in list_ids:
canvas.delete(el)
list_ids = []
generate_enemy_ships()
b0 = Button(tk, text="Показать корабли противника", command=button_show_enemy)
b0.place(x=size_canvas_x + 20, y=30)
b1 = Button(tk, text="Начать заново!", command=button_begin_again)
b1.place(x=size_canvas_x + 20, y=70)
def add_to_all(event):
_type = 0 # ЛКМ
if event.num == 3:
_type = 1 # ПКМ
# print(_type)
mouse_x = canvas.winfo_pointerx() - canvas.winfo_rootx()
mouse_y = canvas.winfo_pointery() - canvas.winfo_rooty()
# print(mouse_x, mouse_y)
ip_x = mouse_x // step_x
ip_y = mouse_y // step_y
print(ip_x, ip_y, "_type:", _type)
canvas.bind_all("<Button-1>", add_to_all) # ЛКМ
canvas.bind_all("<Button-3>", add_to_all) # ПКМ
def generate_enemy_ships():
global enemy_ships
ships_list = []
# генерируем список случайных длин кораблей
for i in range(0, ships):
ships_list.append(random.choice([ships_len1, ships_len2, ships_len3, ships_len4]))
# print(ships_list)
# подсчет суммарной длины кораблей
sum_1_all_ships = sum(ships_list)
sum_1_enemy = 0
while sum_1_enemy != sum_1_all_ships:
# Обнуляем массив кораблей врага
# +1 для доп. линии справа и снизу, для успешных проверок генерации противника
enemy_ships = [[0 for i in range(s_x + 1)] for i in range(s_y + 1)]
for i in range(0, ships):
len = ships_list[i]
horizont_vertikal = random.randrange(1, 3) # 1- горизонтальное 2 - вертикальное
primerno_x = random.randrange(0, s_x)
if primerno_x + len > s_x:
primerno_x = primerno_x - len
primerno_y = random.randrange(0, s_y)
if primerno_y + len > s_y:
primerno_y = primerno_y - len
# print(horizont_vertikal, primerno_x,primerno_y)
if horizont_vertikal == 1:
if primerno_x + len <= s_x:
for j in range(0, len):
try:
check_near_ships = 0
check_near_ships = enemy_ships[primerno_x][primerno_y - 1] + \
enemy_ships[primerno_x][primerno_y + j] + \
enemy_ships[primerno_x][primerno_y + j + 1] + \
enemy_ships[primerno_x + 1][primerno_y + j + 1] + \
enemy_ships[primerno_x - 1][primerno_y + j + 1] + \
enemy_ships[primerno_x + 1][primerno_y + j] + \
enemy_ships[primerno_x - 1][primerno_y + j]
# print(check_near_ships)
if check_near_ships == 0: # записываем в том случае, если нет ничего рядом
enemy_ships[primerno_x][primerno_y + j] = i + 1 # записываем номер корабля
except Exception:
pass
if horizont_vertikal == 2:
if primerno_y + len <= s_y:
for j in range(0, len):
try:
check_near_ships = 0
check_near_ships = enemy_ships[primerno_x - 1][primerno_y] + \
enemy_ships[primerno_x + j][primerno_y] + \
enemy_ships[primerno_x + j + 1][primerno_y] + \
enemy_ships[primerno_x + j + 1][primerno_y + 1] + \
enemy_ships[primerno_x + j + 1][primerno_y - 1] + \
enemy_ships[primerno_x + j][primerno_y + 1] + \
enemy_ships[primerno_x + j][primerno_y - 1]
# print(check_near_ships)
if check_near_ships == 0: # записываем в том случае, если нет ничего рядом
enemy_ships[primerno_x + j][primerno_y] = i + 1 # записываем номер корабля
except Exception:
pass
# делаем подсчет 1ц
sum_1_enemy = 0
for i in range(0, s_x):
for j in range(0, s_y):
if enemy_ships[j][i] > 0:
sum_1_enemy = sum_1_enemy + 1
# print(sum_1_enemy)
# print(ships_list)
print(enemy_ships)
generate_enemy_ships()
while app_running:
if app_running:
tk.update_idletasks()
tk.update()
time.sleep(0.005)

View File

@ -0,0 +1,40 @@
from unittest import TestCase
class TestShipField(TestCase):
def test_action(self):
self.fail()
def test_target(self):
self.fail()
def test_clear_marker(self):
self.fail()
def test_set_ship(self):
self.fail()
def test_shoot(self):
ship_field = ShipField()
ship_field.field
self.fail()
def test_check_possible(self):
self.fail()
def test_check_blocked(self):
self.fail()
def test_set_ship_size(self):
self.fail()
def test_set_ship_direction(self):
ship_field = ShipField()
ship_field.set_ship_direction(1)
self.assertEqual(ship_field.ship_direction)
ship_field.set_ship_direction()
self.assertEqual(ship_field.ship_direction, 0)
def test_toggle_field_mode(self):
self.fail()

View File

0
HNS/__init__.py Normal file
View File