Projekt_Sztuczna_Inteligencja/minefield.py

82 lines
2.7 KiB
Python
Raw Normal View History

import json
2021-03-26 16:36:21 +01:00
import agent as ag
2021-03-14 19:18:23 +01:00
import project_constants as const
2021-03-12 11:49:19 +01:00
import tile as tl
from mine_models import standard_mine as sm
from mine_models import time_mine as tm
from mine_models import chained_mine as cm
2021-03-12 11:49:19 +01:00
2021-03-26 16:36:21 +01:00
2021-03-12 11:49:19 +01:00
class Minefield:
def __init__(self, json_path):
self.turn = 0
2021-03-26 16:36:21 +01:00
self.agent = ag.Agent(const.MAP_RANDOM_10x10)
2021-03-12 11:49:19 +01:00
# open JSON with minefield info
with open(json_path) as json_data:
data = json.load(json_data)
2021-03-12 11:49:19 +01:00
# create matrix of a desired size, fill it with default tile objects
self.matrix = [
[
tl.Tile((row, column)) for column in range(const.V_GRID_HOR_TILES)
] for row in range(const.V_GRID_VER_TILES)
]
2021-03-12 11:49:19 +01:00
# iterate through tiles, set their colors and add mines
for row in range(const.V_GRID_VER_TILES):
for column in range(const.V_GRID_HOR_TILES):
2021-03-12 11:49:19 +01:00
# load tile's data from json
tile_data = data[f"{row},{column}"]
# if there is a mine, create & assign new Mine object (type recognition included)
if tile_data["mine"] is not None:
mine = self._create_mine(tile_data["mine"], row, column)
self.matrix[row][column].mine = mine
self.matrix[row][column].color = tile_data["color"].upper()
2021-03-14 19:18:23 +01:00
# ================ #
# === MOVEMENT === #
# ================ #
# check if sapper's destination is accessible
# If Agent comes upon a tile with a mine his starting position shall be reestablished
def is_valid_move(self, target_row: int, target_column: int):
if 0 <= target_row < const.V_GRID_VER_TILES \
and 0 <= target_column < const.V_GRID_HOR_TILES \
and self.matrix[target_row][target_column].mine is None:
return True
return False
2021-03-14 19:18:23 +01:00
# distinguishes new mine's type and creates appropriate object
def _create_mine(self, mine_data, row, column):
mine_type = mine_data["mine_type"]
# TIME MINE
if mine_type == "time":
timer = mine_data["timer"]
mine = tm.TimeMine((row, column), int(timer))
# CHAINED MINE
elif mine_type == "chained":
if mine_data["predecessor"] is not None:
# locate predecessor
2021-04-11 19:29:12 +02:00
row, column = map(int, mine_data["predecessor"].split(','))
# get predecessor object and assign it to the new mine
predecessor = self.matrix[row][column].mine
mine = cm.ChainedMine((row, column), predecessor)
else:
mine = cm.ChainedMine((row, column))
# STANDARD MINE
else:
mine = sm.StandardMine((row, column))
return mine