102 lines
2.5 KiB
Python
102 lines
2.5 KiB
Python
from tkinter import *
|
|
from ShipField import ShipField
|
|
|
|
|
|
my_field = ShipField()
|
|
enemy_field = ShipField()
|
|
|
|
active_field = my_field
|
|
|
|
|
|
def draw_field(window, field, col_offset):
|
|
buttons = []
|
|
for r in range(0, field.field_size):
|
|
for c in range(0, field.field_size):
|
|
btn = Button(window, text='', width=5, height=2)
|
|
btn.grid(column=c + col_offset, row=r)
|
|
btn.bind('<Button-1>', lambda e, x=r, y=c: left_button_click(buttons, x, y))
|
|
btn.bind('<Button-3>', right_button_click)
|
|
btn.bind('<Enter>', lambda e, x=r, y=c: button_enter(buttons, x, y))
|
|
buttons.append(btn)
|
|
colorize(field, buttons)
|
|
return buttons
|
|
|
|
|
|
def colorize(field, buttons):
|
|
for i in range(len(buttons)):
|
|
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'
|
|
if "+" in field[i]:
|
|
bg = 'orange'
|
|
if "r" in field[i]:
|
|
bg = 'red'
|
|
buttons[i].configure(bg=bg)
|
|
|
|
|
|
def keypress_handler(e):
|
|
global active_field
|
|
if e.keysym.isnumeric():
|
|
active_field.set_ship_size(e.keysym)
|
|
else:
|
|
if e.keysym == 'm':
|
|
active_field.toggle_field_mode()
|
|
|
|
|
|
def left_button_click(buttons, row, col):
|
|
global active_field
|
|
|
|
active_field.action(row, col)
|
|
colorize(active_field, buttons)
|
|
|
|
|
|
def right_button_click(unused):
|
|
global active_field
|
|
|
|
active_field.toggle_ship_direction()
|
|
|
|
|
|
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_field.clear_marker()
|
|
enemy_field.target(row, col)
|
|
|
|
colorize(my_field, my_buttons)
|
|
colorize(enemy_field, enemy_buttons)
|
|
|
|
|
|
window = Tk()
|
|
window.title("Ship Craft!")
|
|
window.geometry('940x410')
|
|
window.bind_all('<KeyPress>', keypress_handler)
|
|
|
|
my_field.toggle_ship_direction()
|
|
my_field.set_ship_size(4)
|
|
my_field.set_ship(1, 1)
|
|
my_field.toggle_ship_direction()
|
|
my_field.set_ship_size(3)
|
|
my_field.set_ship(0, 6)
|
|
my_field.set_ship_size(1)
|
|
my_field.set_ship(7, 3)
|
|
|
|
my_buttons = draw_field(window, my_field, 0)
|
|
enemy_buttons = draw_field(window, enemy_field, 11)
|
|
|
|
lbl = Label(window, text='', width=5, height=2)
|
|
lbl.grid(column=10, row=0)
|
|
|
|
window.mainloop() |