WiP commit to not loose changes

This commit is contained in:
Artur Savitskiy 2024-02-15 18:27:17 +01:00
parent 151a461de0
commit 381341e3cd
2 changed files with 265 additions and 184 deletions

View File

@ -1,7 +0,0 @@
from enum import Enum
class FieldMode(Enum):
Placing = 0
Friendly = 1
Enemy = 2

View File

@ -1,11 +1,19 @@
from tkinter import * from tkinter import *
from ShootResult import ShootResult from enum import Enum
from FieldMode import FieldMode
my_buttons = []
enemy_buttons = []
field_size = 10 field_size = 10
mode = FieldMode.Placing active_field = 0
ship_size = 4
ship_direction = 0 ship_size_left = 4
ship_direction_left = 0
field_mode_left = 0
ship_size_right = 4
ship_direction_right = 0
field_mode_right = 0
empty_field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', empty_field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
@ -18,206 +26,286 @@ empty_field = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
my_field = list(empty_field) my_field = list(empty_field)
enemy_field = list(empty_field) enemy_field = list(empty_field)
buttons = []
# 1. Определите перечисление (Enum) ShootResult со следующими значениями:
# EMPTY (мимо), DAMAGED (ранен), KILLED (убит), UNDEFINED (действие не определено)
class ShootResult(Enum):
EMPTY = "EMPTY"
DAMAGED = "DAMAGED"
KILLED = "KILLED"
UNDEFINED = "UNDEFINED"
def set_ship(field, row, col, ship_size, direction):
if row < 0 or row > field_size:
return
if col < 0 or col > field_size:
return
index = row * field_size + col
if direction == 0:
if field_size - row < ship_size:
return
for r in range(row, row + ship_size):
index = r * field_size + col
field[index] = "1"
if direction == 1:
if field_size - col < ship_size:
return
for c in range(col, col + ship_size):
index = row * field_size + c
field[index] = "1"
def shoot(field, row, col): def shoot(field, row, col):
if row < 0 or row > field_size - 1: if row < 0 or row > field_size - 1:
return ShootResult.Undefined return ShootResult.UNDEFINED
if col < 0 or col > field_size - 1: if col < 0 or col > field_size - 1:
return ShootResult.Undefined return ShootResult.UNDEFINED
index = row * field_size + col index = row * field_size + col
value = (field[index]).strip() if (field[index]).strip() == "":
field[index] = "0"
if value == '': return ShootResult.EMPTY
field[index] = '0' elif (field[index]).strip() == "1":
return ShootResult.Empty field[index] = "\\"
elif value == '1': return ShootResult.DAMAGED
field[index] = '\\' else:
return ShootResult.Damaged return ShootResult.UNDEFINED
return ShootResult.Undefined
def set_ship(field, row, col, size, direction): def draw_field(window, field, col_offset):
# 0. Проверка стартовой точки (находится ли в поле) buttons = []
if row < 0 or row > field_size - 1:
return
if col < 0 or col > field_size - 1:
return
# 1. Нахождение стартовой точки
index = row * field_size + col
# 2. Определяем направление и в зависимости от него
# 2.1 Если вниз - то сравниваем размер поля (field_size=10) - row и size (field_size - row > size или row + size < field_size)
if direction == 0:
if field_size - row < size:
# 3. Если не помещается, то корабль не ставим
return
# 4. А если помещается - ставим корабль, т.е. (row,col) до (row+size,col) заполняем единичками
for r in range(row, row + size):
index = r * field_size + col
field[index] = '1'
# 2.2 Если вправо - то сравниваем field_size - col и size (field_size - col > size или col + size < field_size)
if direction == 1:
if field_size - col < size:
# 3. Если не помещается, то корабль не ставим
return
# 4. А если помещается - ставим корабль, т.е. (row,col) до (row,col+size) заполняем единичками
for c in range(col, col + size):
index = row * field_size + c
field[index] = '1'
def draw_field(window, field):
for r in range(0, field_size): for r in range(0, field_size):
for c in range(0, field_size): for c in range(0, field_size):
btn = Button(window, text="", bg='white', width=5, height=2) index = r * field_size + c
btn.grid(column=c, row=r) btn = Button(window, text='', width=5, height=2)
btn.grid(column=c + col_offset, row=r)
btn.bind('<Enter>', lambda e, row=r, col=c: button_hover(my_field, row, col)) btn.bind('<Button-1>', lambda e, x=r, y=c: left_button_click(field, buttons, x, y))
btn.bind('<Button-1>', lambda e, x=r, y=c: button_action(my_field, x, y)) btn.bind('<Button-3>', right_button_click)
btn.bind('<Button-3>', rotate_ship) btn.bind('<Enter>', lambda e, x=r, y=c: button_enter(field, buttons, x, y))
buttons.append(btn) buttons.append(btn)
colorize(field, buttons)
return buttons
def rotate_ship(e): def colorize(field, buttons):
global ship_direction for i in range(len(field)):
bg = "white"
if field[i] == "1":
bg = 'pink'
if field[i] == "\\":
bg = 'red'
if field[i] == "0":
bg = 'black'
if field[i] == "p":
bg = 'blue'
buttons[i].configure(bg=bg)
def keypress_handler(e):
global ship_size_left
global field_mode_left
global ship_size_right
global field_mode_right
if e.keysym.isnumeric():
number = int(e.keysym)
if 1 <= number <= 4:
if active_field == 0:
ship_size_left = number
else:
ship_size_right = number
else:
if e.keysym == 'm':
if active_field == 0:
field_mode = field_mode_left
else:
field_mode = field_mode_right
if field_mode == 0:
field_mode = 1
else:
field_mode = 0
if active_field == 0:
field_mode_left = field_mode
else:
field_mode_right = field_mode
def left_button_click(field, buttons, row, col):
global ship_size_left
global ship_direction_left
global ship_size_right
global ship_direction_right
if active_field == 0:
field_mode = field_mode_left
ship_size = ship_size_left
ship_direction = ship_direction_left
else:
field_mode = field_mode_right
ship_size = ship_size_right
ship_direction = ship_direction_right
if field_mode == 0:
if check_possible(field, row, col, ship_size, ship_direction):
set_ship(field, row, col, ship_size, ship_direction)
elif field_mode == 1:
shoot(field, row, col)
colorize(field, buttons)
def right_button_click(d):
global ship_direction_left
global ship_direction_right
global field_mode_left
global field_mode_right
if active_field == 0:
field_mode = field_mode_left
ship_direction = ship_direction_left
else:
field_mode = field_mode_right
ship_direction = ship_direction_right
if field_mode == 0:
if ship_direction == 0:
ship_direction = 1
else:
ship_direction = 0
if active_field == 0:
ship_direction_left = ship_direction
else:
ship_direction_right = ship_direction
def button_enter(field, buttons, row, col):
global active_field
global ship_direction_left
global ship_direction_right
global ship_size_left
global ship_size_right
global field_mode_left
global field_mode_right
if buttons == my_buttons:
active_field = 0
elif buttons == enemy_buttons:
active_field = 1
if active_field == 0:
field_mode = field_mode_left
ship_direction = ship_direction_left
ship_size = ship_size_left
other_field = enemy_field
other_buttons = enemy_buttons
else:
field_mode = field_mode_right
ship_direction = ship_direction_right
ship_size = ship_size_right
other_field = my_field
other_buttons = my_buttons
for i in range(0, len(other_field)):
if other_field[i] == "p":
other_field[i] = ''
colorize(other_field, other_buttons)
if field_mode == 0:
for i in range(0, len(field)):
if field[i] == "p":
field[i] = ''
if check_possible(field, row, col,ship_size, ship_direction):
if ship_direction == 0:
for r in range(row, row + ship_size):
field[r * field_size + col] = "p"
if ship_direction == 1:
for c in range(col, col + ship_size):
field[row * field_size + c] = "p"
colorize(field, buttons)
def check_possible(field, row, col, ship_size, ship_direction):
# Функция должна возвращать True, если можно поставить сюда корабль,
# в противном случае - False
if ship_direction == 0: if ship_direction == 0:
ship_direction = 1 # Здесь мы знаем, что корабль помещается на поле.
else: if field_size - row >= ship_size:
ship_direction = 0 # Теперь нужно проверить, не заблокировано ли какое-то из полей,
for r in range(row, row + ship_size):
if not check_blocked(field, r, col):
return False
return True
if ship_direction == 1:
def button_hover(field, row, col): if field_size - col >= ship_size:
clear_placing(field) for c in range(col, col + ship_size):
place_ship(field, row, col, ship_size, ship_direction) if not check_blocked(field, row, c):
colorize(field) return False
return True
def clear_placing(field):
for r in range(0, field_size):
for c in range(0, field_size):
index = r*field_size+c
if field[index] == 'p':
field[index] = ''
def place_ship(field, row, col, size, direction):
blocked = False
if row < 0 or row > field_size - 1:
return
if col < 0 or col > field_size - 1:
return
if direction == 0:
if field_size - row < size:
return
for r in range(row, row + size):
if check_blocked(field, r, col):
blocked = True
break
if not blocked:
for r in range(row, row + size):
field[r * field_size + col] = 'p'
if direction == 1:
if field_size - col < size:
return
for c in range(col, col + size):
if check_blocked(field, row, c):
blocked = True
break
if not blocked:
for c in range(col, col + size):
field[row * field_size + c] = 'p'
def check_blocked(field, row, col):
for r in range(row-1, row+2):
for c in range(col-1, col+2):
if r < 0 or r > field_size - 1:
continue
if c < 0 or c > field_size - 1:
continue
if (field[r*field_size + c]).strip() != '':
return True
return False return False
def colorize(field): def check_blocked(field, row, col):
for r in range(0, field_size): # Функция возвращает True, если все клетки вокруг клетки с координатами row, col
for c in range(0, field_size): # либо находятся за пределами поля, либо в них нет корабля/они пустые
index = r*field_size+c for r in range(row - 1, row + 2):
btn = buttons[index] for c in range(col - 1, col + 2):
bg = 'white' if 0 <= r < field_size and 0 <= c < field_size:
cell = (field[r * field_size + c]).strip()
if field[index] == '1': if cell != '' and cell != 'p':
bg = 'pink' return False
elif field[index] == '\\': return True
bg = 'red'
elif field[index] == '0':
bg = 'black'
elif field[index] == 'p':
bg = 'blue'
btn.configure(bg=bg)
def button_action(field, row, col):
if mode == FieldMode.Enemy:
shoot(field, row, col)
colorize(field)
elif mode == FieldMode.Friendly:
colorize(field)
elif mode == FieldMode.Placing:
set_ship(field, row, col, ship_size, ship_direction)
def keypress_handler(e):
global ship_size
if e.keysym in '1234':
ship_size = int(e.keysym)
window = Tk() window = Tk()
window.title("Ship Craft!") window.title("Ship Craft!")
window.geometry('450x410') window.geometry('940x410')
window.bind_all('<KeyPress>', keypress_handler) 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))
#set_ship(my_field, 1, 1, 4, 1) lbl = Label(window, text='', width=5, height=2)
#set_ship(my_field, 0, 6, 3, 0) lbl.grid(column=10, row=0)
#set_ship(my_field, 9, 9, 1, 0)
#set_ship(my_field, 0, 0, 1, 0)
#set_ship(my_field, 9, 0, 1, 0)
#set_ship(my_field, 9, 2, 4, 1)
draw_field(window, my_field)
colorize(my_field)
window.mainloop() window.mainloop()
for r in range(0, field_size):
blocked_string = ""
ship_string = ""
for c in range(0, field_size):
blocked_string += str(check_blocked(my_field, r, c))[0] + ", "
ship_string += my_field[r * field_size + c] + ', '
print(blocked_string[:-2] + ' ' + ship_string[:-2])
print("********************************************************************")
for r in range(0, field_size):
possible_string = ""
impossible_string = ""
for c in range(0, field_size):
possible_string += str(check_possible(my_field, r, c))[0] + ", "
impossible_string += my_field[r * field_size + c] + ', '
print(possible_string[:-2] + ' ' + impossible_string[:-2])