Compare commits

..

10 Commits

46 changed files with 777 additions and 171 deletions

View File

@ -1,13 +1,15 @@
from doctest import master
from tkinter import *
WINDOW_X = 533 + 1200
WINDOW_Y = 950
FRAME_WIDTH = 533
FRAME_HEIGHT = 533
# WINDOW_X = 533 + 1200
# WINDOW_Y = 950
# FRAME_WIDTH = 533
# FRAME_HEIGHT = 533
#
# # Size of small image
# IMAGE_SIZE = 50
# Size of small image
IMAGE_SIZE = 50
from resources.Globals import *
step = IMAGE_SIZE + 3
@ -15,32 +17,38 @@ step = IMAGE_SIZE + 3
class Field(object):
def __init__(self):
self.win = Tk()
self.width = 533
self.height = 533
self.width = 555
self.height = 555
self.image_size = 50
self.rows = 10
self.columns = 10
self.x_start = 3
self.y_start = 3
self.x_start = 5
self.y_start = 5
self.state_of_cell_array = [[0 for i in range(3)] for j in range(200)]
self.field_state_array = [[False for i in range(self.rows)] for j in range(self.columns)]
self.small_image_array = [[0 for i in range(self.rows)] for j in range(self.columns)]
self.large_image_array = [[0 for i in range(self.rows)] for j in range(self.columns)]
self.cell_expense = [0 for i in range(self.rows * self.columns)]
self.visited_mines = []
# Modified by Artem to search in the status area
self.canvas_small_images = []
self.rectangle = 0
self.mines_coord = []
self.main_frame = Frame(master, width=FRAME_WIDTH, height=FRAME_HEIGHT, bd=0)
self.main_frame.pack(anchor=NW)
self.small_field_canvas = Canvas(self.main_frame, width=FRAME_WIDTH, height=FRAME_HEIGHT, highlightthickness=0,
bg='light gray')
bg='black')
self.small_field_canvas.pack()
self.large_image_canvas = Canvas(self.win, width=WINDOW_X - 533 - 20, height=900, highlightthickness=0,
bg='gray')
self.large_image_canvas.place(x=FRAME_WIDTH + 5, y=3)
self.flag_img = PhotoImage(master=self.small_field_canvas, file="../../files/flag/Flaga.png")
# Clear Canvases
def Moving(self):
self.large_image_canvas.delete('all')
@ -55,6 +63,7 @@ class Field(object):
# Putting small images
for i in range(self.columns):
for j in range(self.rows):
small_image_name = self.small_image_array[column][row]
self.small_field_canvas.image = small_image_name
@ -62,12 +71,18 @@ class Field(object):
self.small_field_canvas.create_image(x, y, anchor=NW, image=small_image_name))
# self.small_field_canvas.create_image(x, y, anchor=NW, image=small_image_name)
for k in range(0, len(self.mines_coord)):
if self.mines_coord[k][0] == i and self.mines_coord[k][1] == j:
new_mine_coord = self.small_field_canvas.coords(self.canvas_small_images[len(self.canvas_small_images) - 1])
self.mines_coord[k] = new_mine_coord
x += self.image_size + self.x_start
row += 1
y += self.image_size + self.y_start
x = self.x_start
column += 1
row = 0
# print(self.mines_coord)
def PuttingLargeImage(self, large_img_name):
self.large_image_canvas.image = large_img_name

View File

@ -1,8 +1,15 @@
from resources.Globals import *
images_coord_list = []
cell_expense_list = []
class Node:
def __init__(self):
self.state = State()
self.parent = None
self.parent = []
self.action = ""
self.priority = 0
class State:
@ -11,6 +18,14 @@ class State:
self.direction = ""
def init_data(coord_list, expense_list):
global images_coord_list
global cell_expense_list
images_coord_list = coord_list
cell_expense_list = expense_list
def successor(state):
node_state_left = Node()
@ -22,153 +37,249 @@ def successor(state):
node_state_left.state = State()
node_state_left.state.coord = state.coord
node_state_left.state.direction = "north"
#node_state_left.parent = state
node_state_left.action = "Left"
node_state_right.state = State()
node_state_right.state.coord = state.coord
node_state_right.state.direction = "south"
#node_state_right.parent = state
node_state_right.action = "Right"
if state.coord[0] + STEP < FRAME_WIDTH:
node_state_forward.state = State()
node_state_forward.state.coord = [state.coord[0] + 53, state.coord[1]]
node_state_forward.state.coord = [state.coord[0] + STEP, state.coord[1]]
node_state_forward.state.direction = state.direction
#node_state_forward.parent = state
node_state_forward.action = "Up"
#return [node_state_left, node_state_right, node_state_forward]
elif state.direction == "west":
node_state_left.state = State()
node_state_left.state.coord = state.coord
node_state_left.state.direction = "south"
#node_state_left.parent = state
node_state_left.action = "Left"
node_state_right.state = State()
node_state_right.state.coord = state.coord
node_state_right.state.direction = "north"
#node_state_right.parent = state
node_state_right.action = "Right"
if state.coord[0] > x_start:
node_state_forward.state = State()
node_state_forward.state.coord = [state.coord[0] - 53, state.coord[1]]
node_state_forward.state.coord = [state.coord[0] - STEP, state.coord[1]]
node_state_forward.state.direction = state.direction
#node_state_forward.parent = state
node_state_forward.action = "Up"
#return [node_state_left, node_state_right, node_state_forward]
elif state.direction == "north":
node_state_left.state = State()
node_state_left.state.coord = state.coord
node_state_left.state.direction = "west"
#node_state_left.parent = state
node_state_left.action = "Left"
node_state_right.state = State()
node_state_right.state.coord = state.coord
node_state_right.state.direction = "east"
#node_state_right.parent = state
node_state_right.action = "Right"
if state.coord[1] > x_start:
node_state_forward.state = State()
node_state_forward.state.coord = [state.coord[0], state.coord[1] - 53]
node_state_forward.state.coord = [state.coord[0], state.coord[1] - STEP]
node_state_forward.state.direction = state.direction
#node_state_forward.parent = state
node_state_forward.action = "Up"
#return [node_state_left, node_state_right, node_state_forward]
elif state.direction == "south":
node_state_left.state = State()
node_state_left.state.coord = state.coord
node_state_left.state.direction = "east"
#node_state_left.parent = state
node_state_left.action = "Left"
node_state_right.state = State()
node_state_right.state.coord = state.coord
node_state_right.state.direction = "west"
#node_state_right.parent = state
node_state_right.action = "Right"
if state.coord[1] + STEP < FRAME_HEIGHT:
node_state_forward.state = State()
node_state_forward.state.coord = [state.coord[0], state.coord[1] + 53]
node_state_forward.state.coord = [state.coord[0], state.coord[1] + STEP]
node_state_forward.state.direction = state.direction
#node_state_forward.parent = state
node_state_forward.action = "Up"
#return [node_state_left, node_state_right, node_state_forward]
if len(node_state_forward.state.coord) != 0:
return [node_state_left, node_state_right, node_state_forward]
else:
return [node_state_left, node_state_right]
def graphsearch(fringe, explored, start_state, end_state_coord):
def get_cell_expense(node):
global images_coord_list
global cell_expense_list
for i in range(0, len(images_coord_list)):
if (images_coord_list[i][0] <= node.state.coord[0] and node.state.coord[0] <= images_coord_list[i][0] + IMAGE_SIZE) and (images_coord_list[i][1] <= node.state.coord[1] and node.state.coord[1] <= images_coord_list[i][1] + IMAGE_SIZE):
return cell_expense_list[i]
def heurystyka(node_now):
if node_now.action == "Left" or node_now.action == "Right":
return node_now.parent[2] + (get_cell_expense(node_now) / 2)
elif node_now.action == "Up":
return node_now.parent[2] + (get_cell_expense(node_now) * 2)
elif node_now.action == "":
return get_cell_expense(node_now)
# def graph_search(fringe, explored, start_state, end_state_coord):
#
# node = Node()
# node.state = start_state
# node.parent = node.state
# fringe.append(node)
# iterator = 0
#
# end_loop = True
# while end_loop:
# if len(fringe) == 0:
# end_loop = False
# #return False
#
# elem = fringe[iterator]
#
# if elem.state.coord == end_state_coord:
# return fringe
#
# explored.append(elem)
#
# another_states = successor(elem.state)
# for i in range(0, len(another_states)):
# n = len(fringe)
# for j in range(0, n):
# if another_states[i].state.coord[0] == fringe[j].state.coord[0] and another_states[i].state.coord[1] == fringe[j].state.coord[1]:
# if another_states[i].state.direction == fringe[j].state.direction:
# break
# else:
# states = []
# for k in range(0, len(fringe)):
# new_state = [fringe[k].state.coord, fringe[k].state.direction]
# states.append(new_state)
# now_state = [another_states[i].state.coord, another_states[i].state.direction]
# if now_state in states:
# break
#
# another_states[i].parent = elem.state
# fringe.append(another_states[i])
# else:
# states = []
# for k in range(0, len(fringe)):
# new_state = [fringe[k].state.coord, fringe[k].state.direction]
# states.append(new_state)
# now_state = [another_states[i].state.coord, another_states[i].state.direction]
#
# if now_state in states:
# break
#
# if another_states[i].state.direction == fringe[j].state.direction:
# another_states[i].parent = elem.state
# fringe.append(another_states[i])
# iterator += 1
def graph_search_A(fringe, explored, start_state, end_state_coord):
node = Node()
node.state = start_state
node.parent = node.state
#node.action = "Right"
node.priority = heurystyka(node)
node.parent = [node.state.coord, node.state.direction, node.priority]
fringe.append(node)
iter = 0
iterator = 0
bool = True
while bool:
end_loop = True
while end_loop:
if len(fringe) == 0:
bool = False
#return False
end_loop = False
# return False
elem = fringe[iter]
elem = fringe[iterator]
if elem.state.coord == end_state_coord:
print("Gotowe!")
bool = False
return fringe
explored.append(elem)
another_states = successor(elem.state)
for i in range(0, len(another_states)):
another_states[i].parent = [elem.state.coord, elem.state.direction, elem.priority]
p = heurystyka(another_states[i])
n = len(fringe)
for j in range(0, n):
if another_states[i].state.coord[0] == fringe[j].state.coord[0] and another_states[i].state.coord[1] == fringe[j].state.coord[1]:
if another_states[i].state.direction == fringe[j].state.direction:
if another_states[i].state.direction == fringe[j].state.direction and p < fringe[j].priority:
another_states[i].priority = p
fringe[j] = another_states[i]
break
else:
# states = []
# for k in range(0, len(fringe)):
# new_state = fringe[k].state
# states.append(new_state)
# now_state = another_states[i].state
# if now_state in states:
# break
states = []
for k in range(0, len(fringe)):
new_state = [fringe[k].state.coord, fringe[k].state.direction]
states.append(new_state)
now_state = [another_states[i].state.coord, another_states[i].state.direction]
if now_state in states:
index = states.index(now_state)
if p < fringe[index].priority:
another_states[i].priority = p
fringe[index] = another_states[i]
break
else:
break
# bool_break = False
# for k in range(0, n):
# if another_states[i].state.coord[0] == fringe[k].state.coord[0] and another_states[i].state.coord[1] == fringe[k].state.coord[1]:
# if another_states[i].state.direction == fringe[k].state.direction:
# bool_break = True
# if bool_break:
# break
another_states[i].parent = elem.state
another_states[i].priority = p
fringe.append(another_states[i])
else:
if another_states[i] in fringe:
n1 = len(fringe)
while n1 > 1:
change = False
for l in range(0, n1 - 1):
if fringe[l].priority > fringe[l + 1].priority:
fringe[l], fringe[l + 1] = fringe[l + 1], fringe[l]
change = True
n1 -= 1
if not change:
break
else:
states = []
for k in range(0, len(fringe)):
new_state = [fringe[k].state.coord, fringe[k].state.direction]
states.append(new_state)
now_state = [another_states[i].state.coord, another_states[i].state.direction]
if now_state in states:
index = states.index(now_state)
if p < fringe[index].priority:
another_states[i].priority = p
fringe[index] = another_states[i]
break
else:
break
if another_states[i].state.direction == fringe[j].state.direction:
another_states[i].parent = elem.state
another_states[i].priority = p
fringe.append(another_states[i])
iter += 1
n2 = len(fringe)
while n2 > 1:
change = False
for h in range(0, n2 - 1):
if fringe[h].priority > fringe[h + 1].priority:
fringe[h], fringe[h + 1] = fringe[h + 1], fringe[h]
change = True
n2 -= 1
if not change:
break
iterator += 1

View File

@ -1,16 +1,18 @@
WINDOW_X = 533 + 1200
WINDOW_Y = 950
FRAME_WIDTH = 533
FRAME_HEIGHT = 533
# WINDOW_X = 533 + 1200
# WINDOW_Y = 950
# FRAME_WIDTH = 533
# FRAME_HEIGHT = 533
#
# # Size of small image
# IMAGE_SIZE = 50
# Size of small image
IMAGE_SIZE = 50
from resources.Globals import *
class Player(object):
def __init__(self):
self.x_start = 3
self.y_start = 3
self.x_start = 5
self.y_start = 5
self.current_x = self.x_start
self.current_y = self.y_start
self.step = IMAGE_SIZE + self.x_start

17
bin/Classess/Track.py Normal file
View File

@ -0,0 +1,17 @@
class Track:
def __init__(self, priority, road):
self.priority = priority
self.road = road
def __eq__(self, other):
try:
return self.priority == other.priority
except AttributeError:
return NotImplemented
def __lt__(self, other):
try:
return self.priority < other.priority
except AttributeError:
return NotImplemented

203
bin/Classess/Travel.py Normal file
View File

@ -0,0 +1,203 @@
import queue
from itertools import permutations, islice
from math import sqrt
import random
from resources.Globals import NUMBER_OF_INDIVIDUALS_FOR_DUEL, NUMBER_OF_POINTS_PERMUTATION, PERCENT_OF_MUTATION, \
PERCENT_OF_OUTGOING_INDIVIDUALS
class Travel:
def __init__(self):
self.points_coord = []
self.points_map = {}
def genetic_algorithm(travel_map):
population = []
road_map = list(travel_map.keys())
points_permutation = list(map(list, islice(permutations(road_map), NUMBER_OF_POINTS_PERMUTATION)))
# Generate the first population
for i in range(0, len(points_permutation)):
road = points_permutation[i]
priority = adaptation_function(points_permutation[i], travel_map)
population.append((priority, road))
while len(population) < 10000:
parent1, parent2 = tournament_selection(population)
child = edge_recombination_crossover(parent1[1], parent2[1])
child_priority = adaptation_function(child, travel_map)
population.append((child_priority, child))
mutation_function(population, travel_map)
population.sort(key=lambda x: x[0], reverse=True)
return population[0]
def adaptation_function(list_points, travel_map):
index_of_point = 0
distance = 0
while True:
if index_of_point < (-len(list_points)):
return round((1 / distance) * 1000000)
if index_of_point == (len(list_points) - 1):
x1 = travel_map.get(list_points[index_of_point])[0]
y1 = travel_map.get(list_points[index_of_point])[1]
x2 = travel_map.get(list_points[-len(list_points)])[0]
y2 = travel_map.get(list_points[-len(list_points)])[1]
index_of_point = -len(list_points) - 1
else:
x1 = travel_map.get(list_points[index_of_point])[0]
y1 = travel_map.get(list_points[index_of_point])[1]
x2 = travel_map.get(list_points[index_of_point + 1])[0]
y2 = travel_map.get(list_points[index_of_point + 1])[1]
index_of_point += 1
distance += sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def tournament_selection(population):
individuals_for_duel1 = []
individuals_for_duel2 = []
population_length = len(population)
while True:
if len(individuals_for_duel1) == NUMBER_OF_INDIVIDUALS_FOR_DUEL and len(individuals_for_duel2) == NUMBER_OF_INDIVIDUALS_FOR_DUEL:
break
if len(individuals_for_duel1) != NUMBER_OF_INDIVIDUALS_FOR_DUEL:
index1 = random.randint(0, population_length - 1)
candidate_for_duel1 = population[index1]
if candidate_for_duel1 not in individuals_for_duel1:
individuals_for_duel1.append(candidate_for_duel1)
if len(individuals_for_duel2) != NUMBER_OF_INDIVIDUALS_FOR_DUEL:
index2 = random.randint(0, population_length - 1)
candidate_for_duel2 = population[index2]
if candidate_for_duel2 not in individuals_for_duel1 and candidate_for_duel2 not in individuals_for_duel2:
individuals_for_duel2.append(candidate_for_duel2)
winner_of_duel1 = max(individuals_for_duel1, key=lambda x: x[0])
winner_of_duel2 = max(individuals_for_duel2, key=lambda x: x[0])
return winner_of_duel1, winner_of_duel2
def edge_recombination_crossover(parent1, parent2):
dict_of_neighbors = generate_dict_of_neighbors(parent1, parent2)
gen_index = random.randint(0, len(parent1) - 1)
gen = parent1[gen_index]
child = []
while True:
child.append(gen)
if len(child) == len(parent1):
return child
for key in dict_of_neighbors.keys():
if gen in dict_of_neighbors[key]:
dict_of_neighbors[key].remove(gen)
if not dict_of_neighbors[gen]:
while True:
# new_gen = random.randint(parent1[0], parent1[-1])
new_gen_index = random.randint(0, len(parent1) - 1)
new_gen = parent1[new_gen_index]
if new_gen not in child:
break
else:
new_gen = dict_of_neighbors[gen][0]
best_neighbor = len(dict_of_neighbors[new_gen])
for neighbor in dict_of_neighbors[gen][1:]:
possible_best_neighbor = len(dict_of_neighbors[neighbor])
if possible_best_neighbor <= best_neighbor:
best_neighbor = possible_best_neighbor
new_gen = neighbor
gen = new_gen
def generate_dict_of_neighbors(parent1, parent2):
dict_of_neighbors = {}
for i in range(0, len(parent1)):
list_of_neighbors = []
element = parent1[i]
if i == 0:
left_neighbor1 = parent1[-1]
right_neighbor1 = parent1[i + 1]
elif i == (len(parent1) - 1):
left_neighbor1 = parent1[i - 1]
right_neighbor1 = parent1[0]
else:
left_neighbor1 = parent1[i - 1]
right_neighbor1 = parent1[i + 1]
list_of_neighbors.extend([left_neighbor1, right_neighbor1])
index = parent2.index(element)
if index == 0:
left_neighbor2 = parent2[-1]
right_neighbor2 = parent2[index + 1]
elif index == (len(parent2) - 1):
left_neighbor2 = parent2[index - 1]
right_neighbor2 = parent2[0]
else:
left_neighbor2 = parent2[index - 1]
right_neighbor2 = parent2[index + 1]
if left_neighbor2 not in list_of_neighbors:
list_of_neighbors.append(left_neighbor2)
if right_neighbor2 not in list_of_neighbors:
list_of_neighbors.append(right_neighbor2)
dict_of_neighbors[element] = list_of_neighbors
return dict_of_neighbors
def mutation_function(population, travel_map):
mutation_percentage = random.random()
if mutation_percentage <= PERCENT_OF_MUTATION:
count_individual_for_mutation = round(len(population) * mutation_percentage)
mutants = set()
for i in range(0, count_individual_for_mutation):
while True:
individual_for_mutation = random.randint(0, len(population) - 1)
if individual_for_mutation not in mutants:
mutants.add(individual_for_mutation)
candidate_mutant = population[individual_for_mutation]
while True:
chromosome1 = random.randint(0, len(candidate_mutant[1]) - 1)
chromosome2 = random.randint(0, len(candidate_mutant[1]) - 1)
if chromosome1 != chromosome2:
candidate_mutant[1][chromosome1], candidate_mutant[1][chromosome2] = candidate_mutant[1][chromosome2], candidate_mutant[1][chromosome1]
candidate_mutant_priority = adaptation_function(candidate_mutant[1], travel_map)
mutant = (candidate_mutant_priority, candidate_mutant[1])
if mutant not in population:
population[individual_for_mutation] = mutant
break
break

Binary file not shown.

Binary file not shown.

View File

@ -1,27 +1,37 @@
import os
import random
import time
from tkinter import *
from bin.Classess.Field import Field
from bin.Classess.Mine import Mine
from bin.Classess.Travel import Travel
from bin.Classess.Player import Player
import bin.Classess.Node as nd
import bin.Classess.Travel as tr
from resources.Globals import *
WINDOW_X = 533 + 1200
WINDOW_Y = 950
FRAME_WIDTH = 533
FRAME_HEIGHT = 533
# Size of small image
IMAGE_SIZE = 50
AMOUNT_OF_MINES = 10
# WINDOW_X = 533 + 1200
# WINDOW_Y = 950
# FRAME_WIDTH = 533
# FRAME_HEIGHT = 533
#
# # Size of small image
# IMAGE_SIZE = 50
#
# AMOUNT_OF_MINES = 10
#
# DELAY_TIME = 0.5
# Creating objects
player = Player()
field = Field()
travel = Travel()
fringe = []
explored = []
action_list = []
images_coord = []
def Arrow(direction):
@ -40,9 +50,25 @@ def Arrow(direction):
# Putting images
def Fill(bool):
global images_coord
if bool:
field.PuttingSmallImages()
travel.points_coord.append(field.small_field_canvas.coords(field.canvas_small_images[0]))
travel.points_coord.extend(field.mines_coord)
for i in range(0, len(travel.points_coord)):
travel.points_map[i + 1] = travel.points_coord[i]
print(travel.points_map)
for i in range(0, len(field.canvas_small_images)):
images_coord.append(field.small_field_canvas.coords(field.canvas_small_images[i]))
# print("Coords List: ", images_coord)
nd.init_data(images_coord, field.cell_expense)
# Drawing red/green rectangles
for el in field.state_of_cell_array:
if el[0] != 0:
@ -58,7 +84,7 @@ def DrawingLargeImage():
field.PuttingLargeImage(large_img_name)
def Next_direction(side):
def NextDirection(action):
# Define next direction
current_direction = player.direction
t = -1
@ -68,9 +94,9 @@ def Next_direction(side):
break
# Write next direction to Player
if side == "Right":
if action == "Right":
player.direction = player.directions[(t + 1) % 4]
elif side == "Left":
elif action == "Left":
player.direction = player.directions[(t - 1) % 4]
return player.direction
@ -87,31 +113,26 @@ def MovingForward():
field.small_field_canvas.move(player.image_canvas_id, 0, player.step)
def Moving(event):
def Moving(action):
# Moving
if event.keysym == "Right":
if action == "Right":
# player.MovingRight()
field.Moving()
Fill(False)
next_direction = Next_direction(event.keysym)
next_direction = NextDirection(action)
Arrow(next_direction)
elif event.keysym == "Left":
elif action == "Left":
# player.MovingLeft()
field.Moving()
Fill(False)
next_direction = Next_direction(event.keysym)
next_direction = NextDirection(action)
Arrow(next_direction)
elif event.keysym == "Up":
elif action == "Up":
player.Moving()
field.Moving()
Fill(False)
MovingForward()
Arrow(player.direction)
# elif event.keysym == "space":
# player.MovingDown()
# field.Moving()
# Fill()
# Arrow(player.arrow_south_image)
def ImagesInArray(directory, array):
@ -135,11 +156,15 @@ def ImagesInArray(directory, array):
if column == 10:
column = 0
row += 1
if row == 10:
break
column += 1
if column == 10:
column = 0
row += 1
if row == 10:
break
def CellDesignation(array, color):
@ -151,67 +176,151 @@ def CellDesignation(array, color):
break
def Action(event):
if event.keysym in ["Right", "Left", "Up", "space"]:
Moving(event)
elif event.keysym in ["1", "2"]:
if event.keysym == "1":
def Action(action):
if action in ["Right", "Left", "Up", "space"]:
Moving(action)
elif action in ["1", "2"]:
if action == "1":
CellDesignation(field.state_of_cell_array, "red")
else:
CellDesignation(field.state_of_cell_array, "green")
# Modified by Artem to search in the status area
def MouseClickEvent(event):
def create_action_list(states, index):
global fringe
#print(len(field.canvas_small_images), field.canvas_small_images)
for i in range(0, len(field.canvas_small_images)):
print(field.small_field_canvas.coords(field.canvas_small_images[i]))
#print("Lewy przycisk myszy zostal nacisniety!")
#node = nd.Node()
#print(node.state.coord, node.state.direction, node.action, node.parent)
#node.state = nd.State()
#node.state.coord = field.small_field_canvas.coords(player.image_canvas_id)
#node.state.direction = "east"
#node.state.coord = field.small_field_canvas.coords(field.canvas_small_images[5])
global action_list
if index == 0:
action_list.reverse()
return True
action_list.append(fringe[index].action)
state_parent = [fringe[index].parent[0], fringe[index].parent[1]]
create_action_list(states, states.index(state_parent))
def MouseClickEvent(track):
global fringe
global explored
global action_list
print("The best individual is: {} {}".format(track[1], track[0]))
for point in range(0, len(track[1]) + 1):
start_position = field.small_field_canvas.coords(player.image_canvas_id)
end_state_coord = []
print("Pierwsza pozycja: {} {}".format(start_position[0], start_position[1]))
#print(node.state.coord, node.state.direction, node.parent, node.action)
#print("Pozycje myszy: {} {}".format(event.x, event.y))
for i in range(0, len(field.canvas_small_images)):
img_coords = field.small_field_canvas.coords(field.canvas_small_images[i])
if (img_coords[0] <= event.x and event.x <= img_coords[0] + IMAGE_SIZE) and (img_coords[1] <= event.y and event.y <= img_coords[1] + IMAGE_SIZE):
end_state_coord = img_coords
if len(end_state_coord) == 2:
print("Koncowa pozycja: {} {}".format(end_state_coord[0], end_state_coord[1]))
if point == len(track[1]):
end_position = travel.points_map[1]
else:
end_position = travel.points_map[track[1][point]]
node = nd.Node()
if len(fringe) == 0:
node.state.coord = field.small_field_canvas.coords(player.image_canvas_id)
node.state.coord = start_position
node.state.direction = "east"
print("Pierwszy state - OK")
else:
node = fringe[len(fringe) - 1]
print("Pozostale states - OK")
states = []
for k in range(0, len(fringe)):
new_state = fringe[k].state.coord
states.append(new_state)
start_node = fringe[-1]
node.state.coord = start_node.state.coord
node.state.direction = start_node.state.direction
fringe.clear()
print("\nLIST IS EMPTY: {}\n".format(fringe))
explored.clear()
print("Czyszczenie list - OK")
action_list.clear()
fringe = nd.graph_search_A(fringe, explored, node.state, end_position)
# fringe = nd.graph_search(fringe, explored, node.state, end_position)
# Successor - only east
fringe = nd.graphsearch(fringe, explored, node.state, end_state_coord)
print("Fringe - OK")
#print(fringe)
print("{}".format(fringe))
states = []
goal_all = []
for i in range(0, len(fringe)):
print('Node{} = State: {} {}, Parent: {} {}, Action: {}'.format(i + 1, fringe[i].state.coord, fringe[i].state.direction, fringe[i].parent.coord, fringe[i].parent.direction, fringe[i].action))
new_state = [fringe[i].state.coord, fringe[i].state.direction]
states.append(new_state)
if end_position[0] == fringe[i].state.coord[0] and end_position[1] == fringe[i].state.coord[1]:
goal_all.append(fringe[i])
elem_min = goal_all[0]
for i in range(1, len(goal_all)):
if elem_min.priority > goal_all[i].priority:
elem_min = goal_all[i]
index = fringe.index(elem_min)
fringe = fringe[:index + 1]
create_action_list(states, -1)
# for i in range(0, len(fringe)):
# print('Node{} = State: {} {}, Parent: {} {} {}, Action: {}'.format(i + 1, fringe[i].state.coord, fringe[i].state.direction, fringe[i].parent[0], fringe[i].parent[1], fringe[i].parent[2], fringe[i].action))
# print(action_list)
# Start moving
AutoMove()
DrawFlag()
time.sleep(SLEEP_AFTER_CHECK_MINE)
# start_position = field.small_field_canvas.coords(player.image_canvas_id)
# end_position = []
#
# # print("Pierwsza pozycja: {} {}".format(start_position[0], start_position[1]))
#
# for i in range(0, len(field.canvas_small_images)):
# img_coords = field.small_field_canvas.coords(field.canvas_small_images[i])
# if (img_coords[0] <= event.x and event.x <= img_coords[0] + IMAGE_SIZE) and (img_coords[1] <= event.y and event.y <= img_coords[1] + IMAGE_SIZE):
# end_position = img_coords
# print("Color cost: ", field.cell_expense[i])
#
# # if len(end_position) == 2:
# # print("Koncowa pozycja: {} {}".format(end_position[0], end_position[1]))
#
# node = nd.Node()
# if len(fringe) == 0:
# node.state.coord = start_position
# node.state.direction = "east"
# else:
# states = []
# for k in range(0, len(fringe)):
# new_state = fringe[k].state.coord
# states.append(new_state)
# start_node = fringe[-1]
#
# node.state.coord = start_node.state.coord
# node.state.direction = start_node.state.direction
#
# fringe.clear()
# explored.clear()
# action_list.clear()
# fringe = nd.graph_search_A(fringe, explored, node.state, end_position)
# # fringe = nd.graph_search(fringe, explored, node.state, end_position)
#
# states = []
# goal_all = []
# for i in range(0, len(fringe)):
# new_state = [fringe[i].state.coord, fringe[i].state.direction]
# states.append(new_state)
# if end_position[0] == fringe[i].state.coord[0] and end_position[1] == fringe[i].state.coord[1]:
# goal_all.append(fringe[i])
#
# elem_min = goal_all[0]
# for i in range(1, len(goal_all)):
# if elem_min.priority > goal_all[i].priority:
# elem_min = goal_all[i]
# index = fringe.index(elem_min)
# fringe = fringe[:index + 1]
#
# create_action_list(states, -1)
#
# # for i in range(0, len(fringe)):
# # print('Node{} = State: {} {}, Parent: {} {} {}, Action: {}'.format(i + 1, fringe[i].state.coord, fringe[i].state.direction, fringe[i].parent[0], fringe[i].parent[1], fringe[i].parent[2], fringe[i].action))
#
# print(action_list)
#
#
#
# # Start moving
# AutoMove()
def PutMines(mines_array):
@ -227,6 +336,9 @@ def PutMines(mines_array):
if mine.array_x == x and mine.array_y == y:
is_equal = True
if not is_equal:
if x == 0 and y == 0:
continue
else:
mine = Mine(x, y)
mines_array.append(mine)
@ -235,7 +347,7 @@ def PutMines(mines_array):
counter += 1
def MinesInArrays(mines_array, directory, imgs_array):
def MinesInArrays(mines_array, directory, imgs_array, bool_mines_coord):
counter = 0
temp_array = []
@ -274,6 +386,99 @@ def MinesInArrays(mines_array, directory, imgs_array):
# Add images in image array
imgs_array[mines_array[i].array_x][mines_array[i].array_y] = temp_array[i]
if bool_mines_coord:
for i in range(len(mines_array)):
field.mines_coord.append([mines_array[i].array_x, mines_array[i].array_y])
def DrawFlag():
field.small_field_canvas.create_image(player.current_x, player.current_y, anchor=NW, image=field.flag_img)
# def IsItMine():
# visited = 0 # 0 - not mine; 1 - on this mine for the first time; 2 - already been on this mine
#
# # Checks if the player is on the mine
# for i in field.mines_coord:
# if i[0] == player.current_x and i[1] == player.current_y:
# visited = 1
# # Checks if the player has already been on this mine
# for y in field.visited_mines:
# if y[0] == player.current_x and y[1] == player.current_y:
# visited = 2
# if visited == 1:
# DrawFlag()
def AutoMove():
for action in action_list:
# Program wait for better illustration
time.sleep(DELAY_TIME)
# Move once
Action(action)
# Check if player on mine and if yes, draw flag
# IsItMine()
# Update main window
field.win.update()
# Draws rectangles that indicate type of cells
def DrawRectangle():
x = 4
y = 4
color = None
# Chose color for rectangle
for i in range(len(field.cell_expense)):
if field.cell_expense[i] == standard_cell_cost:
color = "None"
elif field.cell_expense[i] == sand_cell_cost:
color = "yellow"
elif field.cell_expense[i] == water_cell_cost:
color = "dodger blue"
elif field.cell_expense[i] == swamp_cell_cost:
color = "green4"
if color != "None":
field.small_field_canvas.create_rectangle(x, y, x + IMAGE_SIZE + 2, y + IMAGE_SIZE + 2, width=2, outline=color)
x += player.step
if x + IMAGE_SIZE + 2 > field.width:
x = 4
y += player.step
def AddCostCellsToArray(amount, cost):
counter = 0
while counter < amount:
r = random.randint(0, 99)
if field.cell_expense[r] == 0:
field.cell_expense[r] = cost
counter += 1
def CostingOfCells():
AddCostCellsToArray(amount_of_sand_cells, sand_cell_cost)
AddCostCellsToArray(amount_of_water_cells, water_cell_cost)
AddCostCellsToArray(amount_of_swamp_cells, swamp_cell_cost)
AddCostCellsToArray(field.rows * field.columns - (amount_of_sand_cells + amount_of_water_cells + amount_of_swamp_cells), standard_cell_cost)
# Draw rectangles
DrawRectangle()
def click_button():
btn.destroy()
label = Label(field.win, text="Wait... AI conquers the world!", fg='black')
label.place(x=50, y=570)
field.win.update()
track = tr.genetic_algorithm(travel.points_map)
track[1].remove(1)
label.config(text=track[1])
field.win.update()
MouseClickEvent(track)
def main():
# Creating the main window of an application
@ -281,14 +486,27 @@ def main():
field.win.title("Sapper")
field.win.configure(bg='gray')
field.win.geometry(win_size)
print(f'Amount of mines: {AMOUNT_OF_MINES}')
global btn
btn = Button(field.win,
text="Search for mines", # текст кнопки
background="#555", # фоновый цвет кнопки
foreground="#ccc", # цвет текста
padx="20", # отступ от границ до содержимого по горизонтали
pady="8", # отступ от границ до содержимого по вертикали
font="24", # высота шрифта
command=click_button
)
btn.place(x=50, y=570)
# Create array with mines objects
mines_array = []
# Put mines on coordinates
PutMines(mines_array)
MinesInArrays(mines_array, "../../files/small_mines_images", field.small_image_array)
MinesInArrays(mines_array, "../../files/large_mines_images", field.large_image_array)
MinesInArrays(mines_array, "../../files/small_mines_images", field.small_image_array, True)
MinesInArrays(mines_array, "../../files/large_mines_images", field.large_image_array, False)
# Filling image arrays
small_directory = "../../files/small_images"
@ -296,6 +514,8 @@ def main():
large_directory = "../../files/large_images"
ImagesInArray(large_directory, field.large_image_array)
CostingOfCells()
# Add arrow image to Player class
images = []
for file in os.listdir("../../files/arrow"):
@ -318,8 +538,8 @@ def main():
# Rectangle(True, "None")
# Rectangle()
# Binding keyboard press to function
field.win.bind("<Key>", Action)
field.small_field_canvas.bind("<Button-1>", MouseClickEvent)
# field.win.bind("<Key>", Action)
# field.small_field_canvas.bind("<Button-1>", MouseClickEvent)
# Starting mainloop for window
field.win.mainloop()

BIN
files/flag/Flaga.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

38
resources/Globals.py Normal file
View File

@ -0,0 +1,38 @@
import random
FRAME_WIDTH = 555
FRAME_HEIGHT = 555
WINDOW_X = FRAME_WIDTH + 1200
WINDOW_Y = 950
# Size of small image
IMAGE_SIZE = 50
MIN_AMOUNT_OF_MINES = 6
MAX_AMOUNT_OF_MINES = 11
AMOUNT_OF_MINES = random.randint(MIN_AMOUNT_OF_MINES, MAX_AMOUNT_OF_MINES)
DELAY_TIME = 0.2
STEP = IMAGE_SIZE + 5
standard_cell_cost = 10
amount_of_sand_cells = 10
sand_cell_cost = 20
amount_of_water_cells = 10
water_cell_cost = 40
amount_of_swamp_cells = 10
swamp_cell_cost = 80
x_start = 5
y_start = 5
NUMBER_OF_INDIVIDUALS_FOR_DUEL = 4
NUMBER_OF_POINTS_PERMUTATION = 10
PERCENT_OF_MUTATION = 0.01
PERCENT_OF_OUTGOING_INDIVIDUALS = 0.03
SLEEP_AFTER_CHECK_MINE = 1

0
resources/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.