Compare commits

...

9 Commits

34 changed files with 629 additions and 288 deletions

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_19" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pythonProject)" project-jdk-type="Python SDK" />
</project>

View File

@ -1,8 +1,7 @@
{
"ExpandedNodes": [
"",
"\\decisionTree"
""
],
"SelectedNode": "\\decisionTree\\decisionTree.sav",
"SelectedNode": "\\C:\\Users\\zmysz\\Desktop\\nowy-inteligentny-traktor",
"PreviewInSolutionExplorer": false
}

Binary file not shown.

Binary file not shown.

82
NN/Generator.py Normal file
View File

@ -0,0 +1,82 @@
from PIL import Image
import random
plants = [[], [], []]
plants[0].append(Image.open("w1.png"))
plants[0].append(Image.open("w2.png"))
plants[0].append(Image.open("w3.png"))
plants[1].append(Image.open("c1.png"))
plants[1].append(Image.open("c2.png"))
plants[1].append(Image.open("c3.png"))
plants[2].append(Image.open("ca1.png"))
plants[2].append(Image.open("ca2.png"))
plants[2].append(Image.open("ca3.png"))
b = [Image.open("b1.png").convert('RGBA'), Image.open("b2.png").convert('RGBA'), Image.open("b3.png").convert('RGBA')]
def generate(water, fertilizer, plantf):
if water == 1:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10), 40 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
if fertilizer:
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if fertilizer:
new_im = Image.new('RGB', (100, 100),
(
50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if random.randint(0, 1) == 1:
new_im = Image.new('RGB', (100, 100),
(50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
else:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10),
40 + random.randint(-10, 10)))
if random.randint(0, 1) == 1: # big
tmp = plants[plantf][random.randint(0, 2)].resize(
(75 + random.randint(-10, 25), 75 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 15), random.randint(0, 15)), tmp)
else:
tmp = plants[plantf][random.randint(0, 2)].resize(
(random.randint(10, 80), random.randint(10, 80))).rotate(random.randint(0, 359))
datas = tmp.getdata()
new_image_data = []
for item in datas:
# change all white (also shades of whites) pixels to yellow
if item[0] in list(range(190, 256)):
new_image_data.append(
(random.randint(0, 10), 255 + random.randint(-150, 0), random.randint(0, 10)))
else:
new_image_data.append(item)
# update image data
tmp.putdata(new_image_data)
new_im.paste(tmp, (random.randint(0, 30), random.randint(0, 30)), tmp)
return new_im
for x in range(0, 1000):
generate(0, 0, random.randint(0, 2)).save('datasets/00/' + str(x) + '.png')
for x in range(0, 1000):
generate(1, 0, random.randint(0, 2)).save('datasets/10/' + str(x) + '.png')
for x in range(0, 1000):
generate(0, 1, random.randint(0, 2)).save('datasets/01/' + str(x) + '.png')
for x in range(0, 1000):
generate(1, 1, random.randint(0, 2)).save('datasets/11/' + str(x) + '.png')

BIN
NN/b1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

BIN
NN/b2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

BIN
NN/b3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

BIN
NN/c1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

BIN
NN/c2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

BIN
NN/c3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

BIN
NN/ca1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 448 KiB

BIN
NN/ca2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 397 KiB

BIN
NN/ca3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 821 KiB

48
NN/trainer.py Normal file
View File

@ -0,0 +1,48 @@
import pathlib
import random
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.transforms import Lambda
device = torch.device('cpu')
def train(model, dataset, n_iter=100, batch_size=2560000):
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.NLLLoss()
dl = DataLoader(dataset, batch_size=batch_size)
model.train()
for epoch in range(n_iter):
for images, targets in dl:
optimizer.zero_grad()
out = model(images.to(device))
loss = criterion(out, targets.to(device))
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('epoch: %3d loss: %.4f' % (epoch, loss))
image_path_list = list(pathlib.Path('./').glob("*/*/*.png"))
random_image_path = random.choice(image_path_list)
data_transform = transforms.Compose([
transforms.Resize(size=(100, 100)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
Lambda(lambda x: x.flatten())
])
train_data = datasets.ImageFolder(root="./datasets",
transform=data_transform,
target_transform=None)
model1 = nn.Sequential(nn.Linear(30000, 10000), nn.ReLU(), nn.Linear(10000, 10000), nn.ReLU(), nn.Linear(10000, 0000), nn.Linear(10000, 4), nn.LogSoftmax(dim=-1)).to(device)
model1.load_state_dict(torch.load("./trained"))
train(model1, train_data)
torch.save(model1.state_dict(), "./trained")

BIN
NN/w1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

BIN
NN/w2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
NN/w3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

View File

@ -1,7 +1,6 @@
from operator import itemgetter
import cart
import copy
from classes import Field
class Istate:
@ -92,7 +91,7 @@ def fieldCost(T,node):
def cost(T, node):
cost = 0
while (node.get_parent() != None):
while node.get_parent() is not None:
cost = cost + fieldCost(T, node)
node = node.get_parent()
@ -154,7 +153,7 @@ def heuristic(goaltest, node):
def print_moves(elem):
moves_list = []
while (elem.get_parent() != None):
while elem.get_parent() is not None:
moves_list.append(elem.get_action())
elem = elem.get_parent()
moves_list.reverse()
@ -184,7 +183,6 @@ def succ(elem):
temp_move_east = elem.get_x() + 1
temp_move_north = elem.get_y() + 1
if cart.Cart.is_move_allowed_succ(elem) == "x + 1":
actions_list.append(("move", (elem.get_direction(), temp_move_east, elem.get_y())))
elif cart.Cart.is_move_allowed_succ(elem) == "y + 1":
@ -194,8 +192,4 @@ def succ(elem):
elif cart.Cart.is_move_allowed_succ(elem) == "x - 1":
actions_list.append(("move", (elem.get_direction(), temp_move_west, elem.get_y())))
return actions_list

14
bfs.py
View File

@ -1,4 +1,3 @@
import sys
import cart
import copy
@ -74,16 +73,12 @@ def goal_test(goaltest,elem):
return False
# def graphsearch(explored, fringe, goaltest, istate, succ): # przeszukiwanie grafu wszerz
def graphsearch(explored, fringe, goaltest, istate): # przeszukiwanie grafu wszerz
def graphsearch(goaltest, istate): # przeszukiwanie grafu wszerz
node = Node(None, istate.get_direction(), None, istate.get_x(), istate.get_y())
fringe = []
#elem = []
explored = []
#action = []
fringe.append(node) # wierzchołki do odwiedzenia
# fringe = [node]
while True:
if not fringe:
return False
@ -109,7 +104,7 @@ def graphsearch(explored, fringe, goaltest, istate): # przeszukiwanie grafu wsz
def print_moves(elem):
moves_list = []
while (elem.get_parent() != None):
while elem.get_parent() is not None:
moves_list.append(elem.get_action())
elem = elem.get_parent()
moves_list.reverse()
@ -139,7 +134,6 @@ def succ(elem):
temp_move_east = elem.get_x() + 1
temp_move_north = elem.get_y() + 1
if cart.Cart.is_move_allowed_succ(elem) == "x + 1":
actions_list.append(("move", (elem.get_direction(), temp_move_east, elem.get_y())))
elif cart.Cart.is_move_allowed_succ(elem) == "y + 1":
@ -149,8 +143,4 @@ def succ(elem):
elif cart.Cart.is_move_allowed_succ(elem) == "x - 1":
actions_list.append(("move", (elem.get_direction(), temp_move_west, elem.get_y())))
return actions_list

View File

@ -1,6 +1,5 @@
import pygame
from screen import SCREEN
global BLACK
# global SCREEN
global BLACK
@ -8,9 +7,9 @@ global gridObjects
global imgTree
global imgTree
imgTree = pygame.image.load('img/tree.png')
gridObjects = {} # Store grid-box objects from Grid Class
class Grid(object):
# ta klasa rysuje kratę na ekranie
def __init__(self, x, y, sx, sy):
@ -27,6 +26,7 @@ class Grid(object):
BLACK = (0, 0, 0)
pygame.draw.rect(SCREEN, BLACK, (self.x, self.y, self.sx, self.sy), self.width)
class Box(object):
# global SCREEN
@ -43,6 +43,7 @@ class Box(object):
# global BLACK
pygame.draw.rect(SCREEN, self.color, pygame.Rect(self.x, self.y, self.sx, self.sy))
class Obstacle(object):
def __init__(self, mouseObj):
self.mseX = mouseObj[0]
@ -54,8 +55,8 @@ class Obstacle(object):
self.y = g.y
self.sx = g.sx
self.sy = g.sy
if self.mseX > self.x and self.mseX < self.x + self.sx:
if self.mseY > self.y and self.mseY < self.y + self.sy:
if self.x < self.mseX < self.x + self.sx:
if self.y < self.mseY < self.y + self.sy:
self.posX = self.x
self.posY = self.y
self.gridBox = grid
@ -66,6 +67,7 @@ class Obstacle(object):
SCREEN.blit(imgTree, (self.posX, self.posY))
# pygame.display.update()
def getGridBoxes(grid_box):
global gridObjects
return gridObjects[grid_box]

View File

@ -25,9 +25,7 @@ class Cart:
def set_y(self, y):
self.y = y
def is_move_allowed(self,
cart_rect): # sprawdza czy dany ruch, który chce wykonać wózek jest możliwy, zwraca prawdę lub fałsz
def is_move_allowed(self, cart_rect): # sprawdza czy dany ruch, który chce wykonać wózek jest możliwy, zwraca prawdę lub fałsz
if self.direction == definitions.CART_DIRECTION_EAST and cart_rect.x + definitions.BLOCK_SIZE < definitions.WIDTH_MAP:
return True
elif self.direction == definitions.CART_DIRECTION_SOUTH and cart_rect.y - definitions.BLOCK_SIZE > 0:
@ -74,4 +72,3 @@ class Cart:
self.direction = 1
else:
self.direction = self.direction + 1

View File

@ -7,6 +7,8 @@ class Field:
self.isFertilized = isFertilized # yes/no
self.fertilizedTime = fertilizedTime # number
class Plant:
def __init__(self, plantType, growthState):
self.plantType = plantType # wheat/carrot/cabbage
@ -22,3 +24,15 @@ class Player:
x = 0
y = 0
rotation = 0
class Watering:
def __init__(self, rain, planted, temperature, sunny, snowy, moist, rotten, dayTime ):
self.rain = rain # yes/no
self.planted = planted # yes/no
self.temperature = temperature # good/bad
self.sunny = sunny
self.snowy = snowy # yes/no
self.moist = moist # yes/no
self.rotten = rotten # yes/no
self.dayTime = dayTime # 1 2 3 4

View File

@ -1,5 +1,6 @@
import random
# Generowanie unikalnej losowej linii tekstu
def generate_unique_line(existing_lines):
while True:
@ -9,6 +10,7 @@ def generate_unique_line(existing_lines):
if line not in existing_lines:
return line
# Generowanie 200 unikalnych linii tekstu
lines = []
while len(lines) < 200:

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# from sklearn.datasets import load_iris
@ -8,7 +9,7 @@ import joblib
X1 = []
view = []
with open("decisionTree/database.txt", 'r') as f:
with open("database.txt", 'r') as f:
for line in f:
line = line.strip()
test_list = [int(i) for i in line]
@ -52,14 +53,14 @@ with open("decisionTree/database.txt", 'r') as f:
view.append(x)
X1.append(test_list)
f = open("decisionTree/learning_set.txt", "w") #zapisuje atrybuty s³ownie
f = open("learning_set.txt", "w") # zapisuje atrybuty s³ownie
for i in view:
f.write(str(i)+"\n")
f.close()
Y1 = []
with open("decisionTree/decissions.txt", 'r') as f: #czyta decyzje
with open("decissions.txt", 'r') as f: # czyta decyzje
for line in f:
line = line.strip()
test = int(line)
@ -69,7 +70,7 @@ dataset = X1
decision = Y1
labels = ['Rain', 'Plant', 'Temperature', 'Sun', 'Snow', 'Moisture', 'Rotten', 'Time']
model = DecisionTreeClassifier(random_state=0, max_depth=20).fit(dataset, decision)
filename = 'decisionTree/decisionTree.sav'
filename = 'decisionTree.sav'
print("Model trained")
print("Decision tree:")
print(export_text(model, feature_names=labels))

View File

@ -1,5 +1,3 @@
# definicje
import os
import pygame
pygame.init()

90
genetic_algorithm.py Normal file
View File

@ -0,0 +1,90 @@
import random
import math
def create_initial_population(population_size, new_list, player):
population = []
for _ in range(population_size):
chromosome = new_list.copy()
chromosome.remove((player.x+1, player.y+1))
random.shuffle(chromosome)
chromosome.insert(0, (player.x+1, player.y+1))
population.append(chromosome)
return population
def calculate_distance(node1, node2):
x1, y1 = node1
x2, y2 = node2
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return distance
def calculate_fitness(individual):
total_distance = 0
num_nodes = len(individual)
for i in range(num_nodes - 1):
node1 = individual[i]
node2 = individual[i + 1]
distance = calculate_distance(node1, node2)
total_distance += distance
if total_distance == 0:
fitness = float('inf')
return fitness
fitness = 1 / total_distance
return fitness
def crossover(parent1, parent2, player):
child = [(player.x+1, player.y+1)] + [None] * (len(parent1) - 1)
start_index = random.randint(1, len(parent1) - 1)
end_index = random.randint(start_index + 1, len(parent1))
child[start_index:end_index] = parent1[start_index:end_index]
remaining_nodes = [node for node in parent2 if node not in child]
child[1:start_index] = remaining_nodes[:start_index - 1]
child[end_index:] = remaining_nodes[start_index - 1:]
return child
def mutate(individual, mutation_rate):
for i in range(1, len(individual)):
if random.random() < mutation_rate:
j = random.randint(1, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
def genetic_algorithm(new_list, player):
max_generations = 200
population_size = 200
mutation_rate = 0.1
population = create_initial_population(population_size, new_list, player)
best_individual = None
best_fitness = float('-inf')
for generation in range(max_generations):
fitness_values = [calculate_fitness(individual) for individual in population]
population = [x for _, x in sorted(zip(fitness_values, population), reverse=True)]
fitness_values.sort(reverse=True)
best_individuals = population[:10]
new_population = best_individuals.copy()
while len(new_population) < population_size:
parent1, parent2 = random.choices(best_individuals, k=2)
child = crossover(parent1, parent2, player)
child = mutate(child, mutation_rate)
new_population.append(child)
for individual in best_individuals:
fitness = calculate_fitness(individual)
if fitness > best_fitness:
best_fitness = fitness
best_individual = individual
population = new_population[:population_size]
return best_individual

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

514
main.py
View File

@ -1,9 +1,19 @@
import joblib
import numpy as np
import pygame
import random
from genetic_algorithm import genetic_algorithm
import torch
from torch import nn
from torchvision import datasets, transforms
from torchvision.transforms import Lambda
from PIL import Image
import astar
from classes import Field, Plant, Fertilizer, Player
from bfs import Node
from bfs import Istate, print_moves, succ
from classes import Field, Player, Watering
from bfs import Istate, succ
from bfs import graphsearch
from board import Grid, Box, Obstacle, getGridBoxes, gridObjects
from screen import SCREEN
@ -14,8 +24,81 @@ from screen import SCREEN
Ucelu = False
SCREENX = 500
SCREENY = 500
device = torch.device('cpu')
model1 = nn.Sequential(nn.Linear(30000, 10000), nn.ReLU(), nn.Linear(10000, 10000), nn.ReLU(), nn.Linear(10000, 10000), nn.Linear(10000, 4), nn.LogSoftmax(dim=-1)).to(device)
# model1.load_state_dict(torch.load("./NN/trained"))
pygame.display.set_caption('Inteligentny Traktor')
plants = [[], [], []]
plants[0].append(Image.open("NN/w1.png"))
plants[0].append(Image.open("NN/w2.png"))
plants[0].append(Image.open("NN/w3.png"))
plants[1].append(Image.open("NN/c1.png"))
plants[1].append(Image.open("NN/c2.png"))
plants[1].append(Image.open("NN/c3.png"))
plants[2].append(Image.open("NN/ca1.png"))
plants[2].append(Image.open("NN/ca2.png"))
plants[2].append(Image.open("NN/ca3.png"))
b = [Image.open("NN/b1.png").convert('RGBA'), Image.open("NN/b2.png").convert('RGBA'), Image.open("NN/b3.png").convert('RGBA')]
def generate(water, fertilizer, plantf):
if water == 1:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10), 40 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
if fertilizer:
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if fertilizer:
new_im = Image.new('RGB', (100, 100),
(
50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if random.randint(0, 1) == 1:
new_im = Image.new('RGB', (100, 100),
(50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
else:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10),
40 + random.randint(-10, 10)))
if random.randint(0, 1) == 1: # big
tmp = plants[plantf][random.randint(0, 2)].resize(
(75 + random.randint(-10, 25), 75 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 15), random.randint(0, 15)), tmp)
else:
tmp = plants[plantf][random.randint(0, 2)].resize(
(random.randint(10, 80), random.randint(10, 80))).rotate(random.randint(0, 359))
datas = tmp.getdata()
new_image_data = []
for item in datas:
# change all white (also shades of whites) pixels to yellow
if item[0] in list(range(190, 256)):
new_image_data.append(
(random.randint(0, 10), 255 + random.randint(-150, 0), random.randint(0, 10)))
else:
new_image_data.append(item)
# update image data
tmp.putdata(new_image_data)
new_im.paste(tmp, (random.randint(0, 30), random.randint(0, 30)), tmp)
return new_im
# COLORS
WHITE = (255, 255, 255)
@ -43,18 +126,19 @@ obstacles = 1
# BFS Variables
startNode = Istate(1, 1, 1)
goalNode = [1, 1]
graph = dict()
pathFound = [] # Store the path in a list box index to draw on later
wheat_path = []
carrot_path = []
cabbage_path = []
def drawGrid(sizex, sizey):
spaceX = SCREENX // sizex
spaceY = SCREENY // sizey
width = 2
counter = 1
for i in range(sizex):
@ -63,16 +147,18 @@ def drawGrid(sizex,sizey):
g = Grid(50 + i*50, 50 + j*50, spaceX, spaceY)
gridObjects[counter] = g
counter += 1
def generateGraph(row, col):
# This function generates a graph based on the gridObjects instantiated!
sample_graph = {'A':['B','C','E'],
'B':['A','D','E'],
'C':['A','F','G'],
'D':['B'],
'E':['A','B','D'],
'F':['C'],
'G':['C']
}
# sample_graph = {'A': ['B', 'C', 'E'],
# 'B': ['A', 'D', 'E'],
# 'C': ['A', 'F', 'G'],
# 'D': ['B'],
# 'E': ['A', 'B', 'D'],
# 'F': ['C'],
# 'G': ['C']
# }
miniG = {}
for grid in range(len(gridObjects)):
@ -133,12 +219,13 @@ def generateGraph(row,col):
return miniG2
def drawGraph(pathF):
# Draws the path given the path-list
global Ucelu
# print(pathF)
if (Ucelu == False):
if not Ucelu:
for grid in pathF:
# g = gridObjects[grid] # Get the grid-box object mentioned in the path
# x = g.x
@ -169,44 +256,6 @@ def drawGraph(pathF):
if player.y > 0:
player.y = player.y - 1
# if player.x < (x/50 - 1):
# a = 1
# if player.x > (x/50 - 1):
# a =2
# if player.y < (y/50 - 1):
# a =3
# if player.y > (y/50 - 1):
# a =4
#
# if a==1:
# # player.x = x/50 - 1
# player.rotation = 0
# if a==2:
# # player.x = x/50 - 1
# player.rotation = 180
# if a==3:
# # player.y = y/50 - 1
# player.rotation = 270
# if a==4:
# # player.y = y/50 - 1
# player.rotation = 90
# tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
# if player.rotation == 180:
# tmpImg = pygame.transform.flip(tmpImg, True, True)
# tmpImg = pygame.transform.flip(tmpImg, True, False)
#
# #player is seen on the way
# SCREEN.blit(tmpImg, (55 + 50 * player.x, 55 + 50 * player.y))
# pygame.display.update()
# # pygame.time.wait(300)
# player.y = y/50 - 1
# player.x = x/50 - 1
# -----------------------------
i = 0
while i < len(T):
j = 0
@ -237,7 +286,6 @@ def drawGraph(pathF):
for obs in obstacleObjects:
obstacleObjects[obs].draw()
for bx in boxObjects:
boxObjects[bx].draw()
@ -255,24 +303,15 @@ def drawGraph(pathF):
# player is seen on the way
SCREEN.blit(tmpImg, (55 + 50 * player.x, 55 + 50 * player.y))
# --------------------------------------
# tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
# # if flip:
# # if flip == True:
# if player.rotation == 180:
# tmpImg = pygame.transform.flip(tmpImg, True, True)
# tmpImg = pygame.transform.flip(tmpImg, True, False)
#
# SCREEN.blit(tmpImg, (55 + 50 * player.x, 55 + 50 * player.y))
pygame.display.update()
pygame.time.wait(300)
SCREEN.fill((WHITE))
SCREEN.fill(WHITE)
# pygame.time.wait(50)
# pygame.draw.rect(SCREEN, WHITE, pygame.Rect(x, y, sx, sy))
Ucelu = True
def UIHandler(mouseObj):
def UIHandler():
# drawGrid(GRIDX, GRIDY)
global Ucelu
drawGrid(10, 10)
@ -288,7 +327,7 @@ def UIHandler(mouseObj):
if pathFound:
drawGraph(pathFound)
# Ucelu = False
def eventHandler(kbdObj, mouseObj):
global boxes
@ -299,7 +338,7 @@ def eventHandler(kbdObj,mouseObj):
global Ucelu
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
pygame.time.wait(DELAY)
@ -345,15 +384,10 @@ def eventHandler(kbdObj,mouseObj):
# If Key_f is pressed, set goal node
if kbdObj[pygame.K_f]:
gBox = getGridBoxes(int(len(gridObjects)))
# gBox = getGridBoxes()
#x = mouseObj[0]
#y = mouseObj[1]
# x = gBox.x
# y = gBox.y
sx = gBox.sx
sy = gBox.sy
# ----------------------------------------
mseX = mouseObj[0]
mseY = mouseObj[1]
@ -363,42 +397,71 @@ def eventHandler(kbdObj,mouseObj):
y = g.y
sx = g.sx
sy = g.sy
if mseX > x and mseX < x + sx:
if mseY > y and mseY < y + sy:
if x < mseX < x + sx:
if y < mseY < y + sy:
posX = x
posY = y
gridBox = grid
# SCREEN.blit(imgTree, (posX, posY))
# ---------------------------------------
bo = Box(posX, posY, sx, sy, BLUE)
boxObjects[boxes] = bo
# boxes += 1
boxes = 1
# goalNode = GRIDX*GRIDX
# goalNode = (10 * (x + 1) + (y + 1) - 10)
# goalNode.state = int(10 * (posX/50 ) + (posY/50) - 10)
# goalNode[0] = int((posX/50)
# goalNode[1] = int(posY/50) - 10
goalNode = [int(posX/50), int(posY/50)]
# goalNode = [10,10]
# drzewo decyzyjne:
W = np.random.randint(2, size=(10, 10, 8))
# Wczytywanie modelu z pliku
labels = ['Rain', 'Planted', 'Temperature', 'Sun', 'Snow', 'Moisture', 'Rotten', 'Time']
loaded_model = joblib.load('decisionTree/decisionTree.sav')
sample = W[goalNode[0]-1][goalNode[1]-1]
# Klasyfikacja przy użyciu wczytanego modelu
predicted_class = loaded_model.predict([sample])
print(labels)
print(sample)
print('Predicted class:', predicted_class)
# Decyzja dotycząca podlania grządek na podstawie przewidzianej etykiety
if predicted_class == [1]:
print('Podlej grządkę')
else:
print('Nie podlewaj grządki')
print('goalNode x = ', goalNode[0], 'goalNode y = ', goalNode[1])
# pygame.display.update()
# goalNode = (x/sx) * (y/sy)
# Delay to avoid multiple spawning of objects
pygame.time.wait(DELAY)
# If Key_x is pressed, spawn tree
if kbdObj[pygame.K_t]:
w = random.randint(0, 1)
f = random.randint(0, 1)
print(w)
print(f)
img = generate(w, f, random.randint(0, 2))
img.save('./test/00/test.png')
data_transform = transforms.Compose([
transforms.Resize(size=(100, 100)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
Lambda(lambda x: x.flatten())
])
datasets.ImageNet
train_data = datasets.ImageFolder(root="./test",
transform=data_transform,
target_transform=None)
model1.eval()
res = model1(train_data[0][0])
if res[0] == res.max():
print("0 0")
if res[1] == res.max():
print("0 1")
if res[2] == res.max():
print("1 0")
if res[3] == res.max():
print("1 1")
# img.show()
if kbdObj[pygame.K_x]:
obs = Obstacle(mouseObj)
obstacleObjects[obstacles] = obs
@ -417,44 +480,22 @@ def eventHandler(kbdObj,mouseObj):
y = g.y
sx = g.sx
sy = g.sy
if mseX > x and mseX < x + sx:
if mseY > y and mseY < y + sy:
if x < mseX < x + sx:
if y < mseY < y + sy:
posX = x
posY = y
T[int((posX/50)-1)][int((posY/50)-1)].plantType = 4
pygame.display.update()
pygame.time.wait(DELAY)
# if Key_SPACE is pressed, start the magic
if kbdObj[pygame.K_SPACE]:
Ucelu = False
gBox = getGridBoxes(1)
x = gBox.x
y = gBox.y
sx = gBox.sx
sy = gBox.sy
x = (player.x +1) * 50
y = (player.y +1) * 50
# tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
# SCREEN.blit(tmpImg, (50 + 50 * player.x, 50 + 50 * player.y))
# pygame.display.update()
#when on it keeps flashing - among others
#bo = Box(x, y, sx, sy, RED)
#boxObjects[boxes] = bo
# boxes += 1
boxes = 1
# startNode.state = (10 * (player.x + 1) + (player.y + 1) - 10)
startNode.x = player.x + 1
startNode.y = player.y + 1
@ -472,12 +513,9 @@ def eventHandler(kbdObj,mouseObj):
graph = generateGraph(GRIDY, GRIDX)
print(graph)
# if startNode != goalNode:
if startNode.x != goalNode[0] or startNode.y != goalNode[1]:
elem = []
move_list = (graphsearch([], [], goalNode, startNode)) # przeszukiwanie grafu wszerz
move_list = (graphsearch(goalNode, startNode)) # przeszukiwanie grafu wszerz
pathFound = move_list
@ -489,32 +527,11 @@ def eventHandler(kbdObj,mouseObj):
pygame.time.wait(DELAY)
# startNode = goalNode
if kbdObj[pygame.K_b]:
Ucelu = False
gBox = getGridBoxes(1)
x = gBox.x
y = gBox.y
sx = gBox.sx
sy = gBox.sy
x = (player.x +1) * 50
y = (player.y +1) * 50
# tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
# SCREEN.blit(tmpImg, (50 + 50 * player.x, 50 + 50 * player.y))
# pygame.display.update()
#when on it keeps flashing - among others
#bo = Box(x, y, sx, sy, RED)
#boxObjects[boxes] = bo
# boxes += 1
boxes = 1
# startNode.state = (10 * (player.x + 1) + (player.y + 1) - 10)
startNode.x = player.x + 1
startNode.y = player.y + 1
@ -529,22 +546,10 @@ def eventHandler(kbdObj,mouseObj):
print('startNode x = ', startNode.x, 'startNode y = ', startNode.y, 'startNode direction = ', startNode.direction)
# startNode = (((player.x + 1)*10 - 9) * (player.y + 1) )
# startNode = 2
# tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
# SCREEN.blit(tmpImg, (55 + 50 * player.x, 55 + 50 * player.y))
# pygame.display.update()
# Delay to avoid multiple spawning of objects
#pygame.time.wait(DELAY)
graph = generateGraph(GRIDY, GRIDX)
print(graph)
# if startNode != goalNode:
if startNode.x != goalNode[0] or startNode.y != goalNode[1]:
elem = []
move_list = (astar.graphsearch([], astar.f, [], goalNode, startNode, T, succ)) # przeszukiwanie grafu wszerz
@ -555,17 +560,150 @@ def eventHandler(kbdObj,mouseObj):
print(move_list)
print('\n')
# Delay to avoid multiple spawning of objects
pygame.time.wait(DELAY)
# else:
# startNode = (10 * (player.x + 1) + (player.y + 1) - 10)
# Ucelu = True
if kbdObj[pygame.K_g]:
global wheat_path
if not wheat_path:
wheat = [(player.x+1, player.y+1), (4, 3), (6, 3), (7, 3), (9, 3), (10, 3), (5, 4), (5, 5), (6, 5), (10, 5), (3, 6), (4, 6), (6, 7), (7, 7), (8, 7)]
wheat_path = genetic_algorithm(wheat, player)
print("Best wheat path:", wheat_path)
if T[player.x][player.y].plantType != 0:
T[player.x][player.y].plantType = 0
if len(wheat_path) > 1:
Ucelu = False
boxes = 1
startNode.x = player.x + 1
startNode.y = player.y + 1
if player.rotation == 0:
startNode.direction = 1
elif player.rotation == 90:
startNode.direction = 2
elif player.rotation == 180:
startNode.direction = 3
elif player.rotation == 270:
startNode.direction = 4
generateGraph(GRIDY, GRIDX)
goalNode = [wheat_path[1][0], wheat_path[1][1]]
if startNode.x != goalNode[0] or startNode.y != goalNode[1]:
move_list = astar.graphsearch([], astar.f, [], goalNode, startNode, T, succ) # przeszukiwanie grafu wszerz
pathFound = move_list
wheat_path.pop(0)
# Delay to avoid multiple spawning of objects
pygame.time.wait(DELAY)
#With it it keeps going, if without it turns off
else:
print("All wheat collected!")
if kbdObj[pygame.K_h]:
global carrot_path
if not carrot_path:
carrot = [(player.x+1, player.y+1), (3, 1), (9, 2), (1, 3), (5, 3), (4, 4), (6, 4), (7, 4), (8, 4), (3, 5), (9, 5), (6, 6), (10, 10)]
carrot_path = genetic_algorithm(carrot, player)
print("Best carrot path:", carrot_path)
if T[player.x][player.y].plantType != 0:
T[player.x][player.y].plantType = 0
if len(carrot_path) > 1:
Ucelu = False
boxes = 1
startNode.x = player.x + 1
startNode.y = player.y + 1
if player.rotation == 0:
startNode.direction = 1
elif player.rotation == 90:
startNode.direction = 2
elif player.rotation == 180:
startNode.direction = 3
elif player.rotation == 270:
startNode.direction = 4
generateGraph(GRIDY, GRIDX)
goalNode = [carrot_path[1][0], carrot_path[1][1]]
if startNode.x != goalNode[0] or startNode.y != goalNode[1]:
move_list = astar.graphsearch([], astar.f, [], goalNode, startNode, T, succ) # przeszukiwanie grafu wszerz
pathFound = move_list
carrot_path.pop(0)
# Delay to avoid multiple spawning of objects
pygame.time.wait(DELAY)
else:
print("All carrot collected!")
if kbdObj[pygame.K_j]:
global cabbage_path
if not cabbage_path:
cabbage = [(player.x+1, player.y+1), (5, 1), (5, 2), (8, 3), (1, 4), (2, 4), (1, 5), (4, 5), (9, 6), (1, 8), (2, 8), (3, 8), (4, 8), (5, 8)]
cabbage_path = genetic_algorithm(cabbage, player)
print("Best cabbage path:", cabbage_path)
if T[player.x][player.y].plantType != 0:
T[player.x][player.y].plantType = 0
if len(cabbage_path) > 1:
Ucelu = False
boxes = 1
startNode.x = player.x + 1
startNode.y = player.y + 1
if player.rotation == 0:
startNode.direction = 1
elif player.rotation == 90:
startNode.direction = 2
elif player.rotation == 180:
startNode.direction = 3
elif player.rotation == 270:
startNode.direction = 4
generateGraph(GRIDY, GRIDX)
goalNode = [cabbage_path[1][0], cabbage_path[1][1]]
if startNode.x != goalNode[0] or startNode.y != goalNode[1]:
move_list = astar.graphsearch([], astar.f, [], goalNode, startNode, T, succ) # przeszukiwanie grafu wszerz
pathFound = move_list
cabbage_path.pop(0)
# Delay to avoid multiple spawning of objects
pygame.time.wait(DELAY)
else:
print("All cabbage collected!")
# Ucelu = False
T = [[Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,2,1,0,0,0),Field(1,3,0,0,0,0),Field(0,3,0,0,0,0),Field(0,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,3,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)],
[Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,0,1,0,0,0),Field(1,3,1,0,0,0),Field(0,0,0,0,0,0),Field(0,0,0,0,0,0),Field(0,0,0,0,0,0),Field(1,3,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)],
@ -576,20 +714,7 @@ T = [[Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,2,1,0,0,0),Field(1,3,0,0,0,0
[Field(1,0,0,0,0,0),Field(0,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,2,0,0,0,0),Field(0,0,1,0,0,0),Field(0,0,1,0,0,0),Field(0,1,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)],
[Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,3,1,0,0,0),Field(1,2,1,0,0,0),Field(0,0,1,0,0,0),Field(0,0,0,0,0,0),Field(0,1,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)],
[Field(1,0,0,0,0,0),Field(0,2,0,0,0,0),Field(1,1,0,0,0,0),Field(1,0,1,0,0,0),Field(0,2,1,0,0,0),Field(0,3,0,0,0,0),Field(0,0,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)],
[Field(1,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,0,0,0,0,0),Field(0,1,1,0,0,0),Field(0,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,1,0,0,0)]]
#T = [[Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,2,1,0,0,0),Field(1,3,0,0,0,0),Field(0,3,0,0,0,0),Field(0,0,1,0,0,0),Field(0,3,0,0,0,0),Field(1,0,1,0,0,0),Field(1,3,0,0,0,0),Field(1,2,1,0,0,0)],
# [Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,0,1,0,0,0),Field(1,3,1,0,0,0),Field(0,0,0,0,0,0),Field(0,0,0,0,0,0),Field(0,2,0,0,0,0),Field(1,1,0,0,0,0),Field(1,0,1,0,0,0),Field(1,1,0,0,0,0)],
# [Field(0,2,1,0,0,0),Field(0,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,0,0,0,0,0),Field(0,2,1,0,0,0),Field(0,1,1,0,0,0),Field(0,2,0,0,0,0),Field(1,0,0,0,0,0),Field(1,0,0,0,0,0),Field(1,1,0,0,0,0)],
# [Field(1,0,1,0,0,0),Field(0,0,1,0,0,0),Field(1,1,1,0,0,0),Field(1,2,0,0,0,0),Field(0,3,1,0,0,0),Field(0,1,0,0,0,0),Field(0,0,0,0,0,0),Field(1,2,0,0,0,0),Field(1,0,0,0,0,0),Field(1,0,0,0,0,0)],
# [Field(1,3,0,0,0,0),Field(0,3,1,0,0,0),Field(1,2,1,0,0,0),Field(1,1,1,0,0,0),Field(0,1,1,0,0,0),Field(0,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,0,1,0,0,0),Field(1,3,0,0,0,0),Field(1,0,1,0,0,0)],
# [Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,1,1,0,0,0),Field(1,2,0,0,0,0),Field(0,1,0,0,0,0),Field(0,2,0,0,0,0),Field(0,1,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,1,1,0,0,0)],
# [Field(1,0,0,0,0,0),Field(0,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,2,0,0,0,0),Field(0,0,1,0,0,0),Field(0,0,1,0,0,0),Field(0,1,0,0,0,0),Field(1,2,1,0,0,0),Field(1,2,1,0,0,0),Field(1,0,0,0,0,0)],
# [Field(1,0,0,0,0,0),Field(0,0,1,0,0,0),Field(1,3,1,0,0,0),Field(1,2,1,0,0,0),Field(0,0,1,0,0,0),Field(0,0,0,0,0,0),Field(0,1,1,0,0,0),Field(1,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,1,1,0,0,0)],
# [Field(1,0,0,0,0,0),Field(0,2,0,0,0,0),Field(1,1,0,0,0,0),Field(1,0,1,0,0,0),Field(0,2,1,0,0,0),Field(0,3,0,0,0,0),Field(0,0,0,0,0,0),Field(1,0,0,0,0,0),Field(1,2,1,0,0,0),Field(1,2,1,0,0,0)],
# [Field(1,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,0,0,0,0,0),Field(0,1,1,0,0,0),Field(0,0,1,0,0,0),Field(0,1,0,0,0,0),Field(1,1,1,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0)]]
[Field(1,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,1,1,0,0,0),Field(1,0,0,0,0,0),Field(0,1,1,0,0,0),Field(0,0,1,0,0,0),Field(0,0,0,0,0,0),Field(1,0,1,0,0,0),Field(1,0,0,0,0,0),Field(1,2,1,0,0,0)]]
# =========================================================================================
@ -608,7 +733,7 @@ while running:
for event in pygame.event.get():
kbd = pygame.key.get_pressed()
mse = pygame.mouse.get_pos()
UIHandler(mse)
UIHandler()
eventHandler(kbd, mse)
pygame.display.update()
# CLOCK.tick(FPS)
@ -637,6 +762,8 @@ while running:
color = (50, 25, 0, 0)
# colour from the beginning
pygame.draw.rect(SCREEN, color, pygame.Rect(50 + 50 * i, 50 + 50 * j, 50, 50))
if T[i][j].plantType == 0:
pygame.draw.rect(SCREEN, color, pygame.Rect(50 + 50 * i, 50 + 50 * j, 50, 50))
if T[i][j].plantType == 1:
SCREEN.blit(imgWheat, (50 + 50 * i, 50 + 50 * j))
if T[i][j].plantType == 2:
@ -646,10 +773,13 @@ while running:
if T[i][j].plantType == 4:
SCREEN.blit(imgTree, (50 + 50 * i, 50 + 50 * j))
j = j + 1
i = i + 1
font = pygame.font.SysFont('comicsans', 22)
labelx = font.render('temp:22 |rain:none |snow:none |sun:cloudy |time:evening', True, (0, 0, 0))
SCREEN.blit(labelx, (10, 10))
i = 0
while i < len(T)+1:
pygame.draw.line(SCREEN, (0, 0, 0), (50 + i * 50, 50), (50 + i * 50, 50 + len(T) * 50), 1)
@ -664,7 +794,6 @@ while running:
for bx in boxObjects:
boxObjects[bx].draw()
tmpImg = pygame.transform.rotate(imgPlayer, player.rotation)
if player.rotation == 180:
tmpImg = pygame.transform.flip(tmpImg, True, True)
@ -674,21 +803,16 @@ while running:
SCREEN.blit(tmpImg, (55 + 50 * player.x, 55 + 50 * player.y))
# if Ucelu == False:
# for bx in boxObjects:
# boxObjects[bx].draw()
font = pygame.font.SysFont('comicsans', 18)
label = font.render('f- punkt końcowy, x- drzewa, spacja- uruchomienie', 1, (0, 0, 0))
label1 = font.render('strzałki-ręczne poruszanie traktorem,', 1, (0, 0, 0))
label2 = font.render('a- obrót w lewo, d- w prawo, w-ruch naprzód', 1, (0, 0, 0))
label3 = font.render('b - uruchom A*', 1, (0, 0, 0))
SCREEN.blit(label, (10, 570))
SCREEN.blit(label1, (10, 590))
SCREEN.blit(label2, (10, 610))
label = font.render('F - cel | X - drzewo', True, (0, 0, 0))
label1 = font.render('ARROWS - ręczne poruszanie', True, (0, 0, 0))
label2 = font.render('A - lewo | D - prawo | W - ruch', True, (0, 0, 0))
label3 = font.render('SPACE - BFS | B - A*', True, (0, 0, 0))
label4 = font.render('G - GA pszenica | H - GA marchewki | J - GA kapusty', True, (0, 0, 0))
SCREEN.blit(label, (10, 555))
SCREEN.blit(label1, (10, 580))
SCREEN.blit(label2, (10, 605))
SCREEN.blit(label3, (10, 630))
SCREEN.blit(label4, (10, 655))
# pygame.display.flip()

View File

@ -1,2 +1,2 @@
import pygame
SCREEN = pygame.display.set_mode([600,665])
SCREEN = pygame.display.set_mode([600, 690])

BIN
test/00/test.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB