I'm making a game of battleships. I created a Ship class to give the ships a location.
After making the class, I had to create all the instances, and I was wondering if there is a way to automate that.
Most of the program is irrelevant, but I'm leaving it in just in case it might affect whether or not it can be automated.
import random
class Ship(object):
def __init__(self, length):
self.length = length
def direction(self):
vh = random.choice(['v','h'])
return vh
def location(self):
space = []
row = random.randint(0, 10-self.length)
column = random.randint(0, 10-self.length)
if self.direction == 'v':
for x in range(self.length):
space.append(f'{column}{row+x}')
else:
for x in range(self.length):
space.append(f'{column}{row+x}')
return space
ships_amount = {
'carrier' : 1,
'battleship' : 2,
'cruiser' : 3,
'destroyer' : 4
}
ships_length = {
'carrier' : 5,
'battleship' : 4,
'cruiser' : 3,
'destroyer' : 2
}
I want to do this:
carrier1 = Ship(ships_length['carrier'])
battleship1 = Ship(ships_length['battleship'])
battleship2 = Ship(ships_length['battleship'])
cruiser1 = Ship(ships_length['cruiser'])
cruiser2 = Ship(ships_length['cruiser'])
cruiser3 = Ship(ships_length['cruiser'])
destroyer1 = Ship(ships_length['destroyer'])
destroyer2 = Ship(ships_length['destroyer'])
destroyer3 = Ship(ships_length['destroyer'])
destroyer4 = Ship(ships_length['destroyer'])
but automated
You can iterate over the ships you want and lookup their lengths to make them:
ships = []
for type_of_ship in ships_amount:
ships.append(Ship(ships_length[type_of_ship]))
or even
ships = [Ship(ships_length[k]) for k in ships_amount]
(In the second example, ky is a shorthand for key, or what is now called type_of_ship in the for loop)
This will give you one of each type of ship.
This will not give you variables named 'carrier1' etc. but you will be able to do stuff with each item in the ships.
e.g.
for ship in ships:
print(ship.length)
To get sthe stated number, or amount of each type of ships, you need to make extra ships in the loop.
By iterating over items() you get a key and value back, which I have called k and v though deserve better names.
The value in your dictionary tells you how many:
ships = []
for k, v in ships_amount.items():
ships.extend([Ship(ships_length[k]) for _ in range(v)])
This gives you the 10 ships you asked for.
If you create a child class of Ship for each Ship model you need, you can group them in a Fleet, then create the fleet directly in one line of code...
Maybe something like this:
import random
class Ship: # this becomes an abstract class, not to be instanciated
# you could have it inherit from ABC (Abstract Base Class)
def __init__(self):
self.length = self.__class__.length
self.heading = None
self.set_heading()
self.location = None
self.set_location()
def set_heading(self):
self.heading = random.choice(['v','h'])
def set_location(self): # this method needs more work to prevent
# ships to occupy the same spot and overlap
space = []
row = random.randint(0, 10 - self.length)
column = random.randint(0, 10 - self.length)
if self.heading == 'v':
for c in range(self.length):
space.append((row, column + c))
elif self.heading == 'h':
for r in range(self.length):
space.append((row + r, column))
self.location = space
def __str__(self):
return f'{self.__class__.__name__} at {self.location}'
class AircraftCarrier(Ship): # every type of ship inherits from the base class Ship
length = 5 # Each class of ship can have its own specifications
# here, length, but it could be firepower, number of sailors, cannons, etc...
class BattleShip(Ship):
length = 4
class Cruiser(Ship):
length = 3
class Destroyer(Ship):
length = 2
class Fleet:
ships_number = {AircraftCarrier : 1,
BattleShip: 2,
Cruiser: 3,
Destroyer: 4}
def __init__(self):
self.ships = [ship() for ship, number in Fleet.ships_number.items()
for _ in range(number)]
def __str__(self):
return '\n'.join([str(ship) for ship in self.ships])
if __name__ == '__main__':
fleet = Fleet() # <-- the creation of the entire Fleet of Ships
print(fleet) # takes now one line of code now
Example Output:
(The locations are randomly assigned and will vary from run to run.)
AircraftCarrier at [(1, 2), (2, 2), (3, 2), (4, 2), (5, 2)]
BattleShip at [(5, 3), (6, 3), (7, 3), (8, 3)]
BattleShip at [(5, 1), (6, 1), (7, 1), (8, 1)]
Cruiser at [(4, 7), (5, 7), (6, 7)]
Cruiser at [(0, 5), (0, 6), (0, 7)]
Cruiser at [(6, 6), (7, 6), (8, 6)]
Destroyer at [(4, 8), (5, 8)]
Destroyer at [(3, 5), (4, 5)]
Destroyer at [(1, 5), (1, 6)]
Destroyer at [(2, 1), (2, 2)]
Adding a new type of ship:
Adding a new type of ship is very easy: It suffices to create a new class inheriting from the abstract base class Ship, and adding the number of the new ships to the fleet composition:
class Submarine(Ship):
length = 1
Fleet.ships_number[Submarine] = 5 # or add this entry directly in the class Fleet data
The fleet has now an additional 5 submarines:
AircraftCarrier at [(4, 1), (5, 1), (6, 1), (7, 1), (8, 1)]
BattleShip at [(5, 5), (6, 5), (7, 5), (8, 5)]
BattleShip at [(0, 0), (1, 0), (2, 0), (3, 0)]
Cruiser at [(5, 2), (5, 3), (5, 4)]
Cruiser at [(2, 0), (3, 0), (4, 0)]
Cruiser at [(7, 7), (8, 7), (9, 7)]
Destroyer at [(4, 3), (5, 3)]
Destroyer at [(2, 1), (2, 2)]
Destroyer at [(0, 8), (1, 8)]
Destroyer at [(3, 6), (3, 7)]
Submarine at [(8, 8)]
Submarine at [(0, 7)]
Submarine at [(3, 4)]
Submarine at [(5, 9)]
Submarine at [(9, 3)]
Related
I have the following function responsible to generate a nested dictionary with integer keys that works inside a for loop, and I want to create a updated list when equal values are found:
# The number of times I want to run
n = 2
# Number of Loops
count = 0
# Init the Hash Table
castar_hash = {}
def run_discrete_time(start, path, count):
'''
Create or Update the Nested Dic, look for equal values and append
a new list based on the 'path' input
Args:
start (list)
path (list)
count (int)
Vars:
start = A simple list with one element
path = A list of Tuples
count = The atual Loop Interaction
'''
# Inserted the 0 because the "discrete time" will init at 0
path_list.insert(0, start)
time_run = list(range(0, len(path_list)+1))
hash = {t:p for t,p in zip(time_run,path_list)}
#* Create a new Dic Key
value_list = ['value', str(count)]
value = "".join(value_list)
castar_hash.update({value:hash})
print(f'\nThe time steps is: {time_run}')
print(f'The Hash table is: {castar_hash}\n')
'''
Need the code here to find the equal values
in the castar_hash and append to a updated list
'''
return updated_list
def main():
for _ in range(n):
'''
some code here who picks the start and path from a deque
already implemented (see the inputs bellow)
'''
count += 1
run_discrete_time(start, path, count)
if __name__ == '__main__':
main()
Let me explain how the function works with inputs: Considering that the loop will run 2 times (since the number of times "n" is 2), for the first call, considering the input:
run_discrete_time([4, 6], [(4, 5), (4, 4),(4, 3),(5, 3),(6, 3),
(7, 3), (8, 3), (8, 2), (8, 1),(9, 1)],
count)
The generated nested dic will be:
castar_hash = {'value1': {0:(4, 6), 1:(4, 5), 2:(4, 4), 3:(4, 3),
4:(5, 3), 5:(6, 3), 6:(7, 3), 7:(8, 3),
8:(8, 2), 9:(8, 1), 10:(9, 1)},
For the second loop with inputs:
run_discrete_time([1, 6], [(2, 6), (4, 4), (4, 6),(4, 5), (4, 4),
(4, 3), (5, 3), (6, 3), (8, 1), (8, 3), (9, 3)],
count)
The updated nest dic will now be:
castar_hash = {'value1': {0:(4, 6), 1:(4, 5), 2:(4, 4), 3:(4, 3),
4:(5, 3), 5:(6, 3), 6:(7, 3), 7:(8, 3),
8:(8, 2), 9:(8, 1), 10:(9, 1)},
'value2': {0:(1, 6), 1:(2, 6), 2:(4, 4), 3:(4, 6),
4:(4, 5), 5:(4, 4), 6:(4, 3), 7:(5, 3),
8:(6, 3), 9:(8, 1), 10:(8, 3), 11:(9,3)}}
My question is: What is the best and most efficient way to extract the equal values in the nested dics for every loop (considering that I can have more than two)? I'm struggling a lot to find a solution for that.
For example, the repeated values in the 'value2' dic is 2:(4, 4) and 9:(8, 1) (in relation to the 'value1' dic), and I would like to return a new list updated as (4,4) inserted in the index 2, and (8,1) at index 9, for example:
#The Path List of Tuples inputed at the second loop
path = [(2, 6), (4, 4), (4, 6),(4, 5), (4, 4),
(4, 3), (5, 3), (6, 3), (8, 1), (8, 3), (9, 3)]
#The New Updated Path List that I want to return since
#the method finded equals values compared to the 'value1' dic:
new_path = [(2, 6), (4, 4), (4, 4) (4, 6),(4, 5), (4, 4),
(4, 3), (5, 3), (6, 3), (8, 1), (8, 1), (8, 3),
(9, 3)]
I'm beginning work on a chess implementation and before going too far down the rabbit hole, I wanted to get the community's input if you wouldn't mind since I'm already at a dead end ha. I'm struggling to figure out the best way to associate the pieces with the coordinates.
Right now, I have a list of list with the various pieces where each list represents a board.
For the coordinates, I used this list comprehension
coordinates = [[(i,j) for i in range(0,8)] for j in range(0,8)]
which gives me a table like this
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0)]
[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)]
[(0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2)]
[(0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3)]
[(0, 4), (1, 4), (2, 4), (3, 4), (4, 4), (5, 4), (6, 4), (7, 4)]
[(0, 5), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), (7, 5)]
[(0, 6), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (7, 6)]
[(0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7)]
Any strong thoughts on how I can associate the piece with their coordinate to find potential moves? I was thinking dictionary at first, but you have multiple pieces of the same type (eg. two knights) and don't think this would be ideal as the board evolved.
Thanks as always.
Funnily enough, I have just been working on exactly this! Previously, I wrote a chess AI but in javascript, however today I have been converting that code into Python for use with a bigger project so the knowledge is fresh in my mind.
Originally, in the JS version, I stored the board effectively as an 8x8 array of strings for each piece (in reality this was inside an object with other data such as castling but that is not important).
However, this method of using an array (list in Python) led to problems due to the way they are passed by reference. The issue was that passing the board state through the negamax algorithm meant that for each move to be considered, the whole array (in JS) would have to be copied to stop the move being made to the original board state.
I got around this by storing the board states as strings which are immutable in Python. I would advise you to start off using lists though as they are much simpler to access and change values even though they will probably end up leading to slowness (from making copies of them) later down the line when you come to optimising.
The actual trick to storing the board state is to use one character for each piece and use upper and lowercase to represent the white and black sides. I stole this technique from the widely used FEN notation and it turns out to be really useful for both displaying and doing operations on the board state!
To see what I mean, you could initialise the starting state with:
state = ["RNBQKBNR", "PPPPPPPP", " ", " ", " ", " ", "pppppppp", "rnbqkbnr"]
state = [list(r) for r in state]
and then you can easily create a display function with:
def display(state):
for r in reversed(state):
print(''.join(r))
then whenever you want to display a given state, you can call display(state) which gives:
rnbqkbnr
pppppppp
PPPPPPPP
RNBQKBNR
Hopefully this helps you out! You can look at the code for my full implementation of a chess AI on github: in Python and in javascript :)
OK it goes like this:
You got 64 cells, traditionally coordinated with letter and digit.
Name each cell numeric so that cell will coordinated: "a1" will be 11, h5 will be 85 etc.
Now for the moves:
Up: (cell value) + 1, Down: (cell value) - 1, Right: (cell value) +
10, Left: (cell value) - 10,
Diagnose: Up-Left: (cell value) - 9, Up-Right: (cell value) +
11, Down-Left: (cell value) - 11, Down-Right: ((cell value) + 9,
And for the Knight: (cell value) + 21, (cell value) - 21, (cell
value) + 12, (cell value) - 12, (cell value) + 8, (cell value) - 8,
(cell value) + 19, (cell value) – 19.
As you can understand, I recently build one by myself ( based on JS if you mind) ha ha.
Good Luck!
As someone mentioned, the most obvious simple implementation is a list of lists, for example in my implementation this logic creates the board, and then pieces are added to it using the add() method:
https://github.com/akulakov/pychess/blob/7176b168568000af721e79887981bcd6467cfbc0/chess.py#L141
I have the following code written in python 2.7 to find n time Cartesian product of a set (AxAxA...xA)-
prod=[]
def cartesian_product(set1,set2,n):
if n>=1:
for x in set1:
for y in set2:
prod.append('%s,%s'%(x,y))
#prod='[%s]' % ', '.join(map(str, prod))
#print prod
cartesian_product(set1,prod,n-1)
else:
print prod
n=raw_input("Number of times to roll: ")
events=["1","2","3","4","5","6"]
cartesian_product(events,events,1)
This works properly when n=1. But changing the parameter value from cartesian_product(events,events,1) to cartesian_product(events,events,2) doesn't work. Seems there's an infinite loop is running. I can't figure where exactly I'm making a mistake.
When you pass the reference to the global variable prod to the recursive call, you are modifying the list that set2 also references. This means that set2 is growing as you iterate over it, meaning the iterator never reaches the end.
You don't need a global variable here. Return the computed product instead.
def cartesian_product(set1, n):
# Return a set of n-tuples
rv = set()
if n == 0:
# Degenerate case: A^0 == the set containing the empty tuple
rv.add(())
else:
rv = set()
for x in set1:
for y in cartesian_product(set1, n-1):
rv.add((x,) + y)
return rv
If you want to perserve the order of the original argument, use rv = [] and rv.append instead.
def cartesian_product(*X):
if len(X) == 1: #special case, only X1
return [ (x0, ) for x0 in X[0] ]
else:
return [ (x0,)+t1 for x0 in X[0] for t1 in cartesian_product(*X[1:]) ]
n=int(raw_input("Number of times to roll: "))
events=[1,2,3,4,5,6]
prod=[]
for arg in range(n+1):
prod.append(events)
print cartesian_product(*prod)
Output:
Number of times to roll: 1
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
you can also pass string in your events list but it'll print string in tuple also.
inside the recursive call cartesian_product(set1,prod,n-1) you are passing the list prod, and you are again appending values to it, so it just grows over time and the inner loop never terminates. Perhaps you might need to change your implementation.
teren = [
'########',
'#s.....#',
'###..#.#',
'#...##.#',
'#.#....#',
'#.####.#',
'#......#',
'###e####'
]
def bfs(teren, start, end):
queue = []
visited = []
queue.append([start])
while queue:
path = queue.pop()
node = path[-1]
x = node[0]
y = node[1]
if node == end:
return path
if node in visited or teren[x][y] == "#":
continue
visited.append(node)
for adjacent in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print(bfs(teren, (1,1), (7, 3)))
This is the code i used to try and navigate this maze type thing, this is the output i get [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 6), (3, 6), (4, 6), (4, 5), (4, 4), (4, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)] while this is the output i need [(1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)]
It seems this is printing out all the walkable coordinates, but I have no idea how to fix that, all the examples online that use grids focus to much on drawing the grid which clutters the actual bfs.
You will get the output you look for if you treat your queue as a queue. This means you don't pop the last element off, but you shift out the first:
replace:
path = queue.pop()
with:
path, queue = queue[0], queue[1:]
or:
path = queue.pop(0)
However deque-objects are better suited for such operations:
from collections import deque
def bfs(teren, start, end):
queue = deque([])
visited = []
queue.append([start])
while queue:
path = queue.popleft()
# ...etc.
I am trying to write a function that completes an A* search with multiple goals. Basically it is searching a grid like structure of the form:
%%%%%%%%%%%%%%%%%%%%
%. ...P .%
%.%%.%%.%%.%%.%% %.%
% %% %..... %.%
%%%%%%%%%%%%%%%%%%%%
for a path from P that goes through all the dots (basically Pacman).
However I have run into a problem with my algorithm (which I attempted to adapt from my A* search for a single goal) as the path it returns does not go through all the dots. This is the path it returns for the above maze:
Path = [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16)]
while a print statement shows that the visited variable has a value at return of:
[(1, 16), (1, 15), (2, 16), (1, 17), (1, 14), (3, 16), (1, 18), (1, 13), (3, 15), (2, 18), (1, 12), (2, 13), (3, 18), (3, 14), (1, 11), (3, 13), (3, 12), (1, 10), (1, 9), (3, 11), (2, 10), (1, 8), (3, 10), (1, 7), (3, 9), (1, 6), (3, 8), (2, 7), (1, 5), (3, 7), (1, 4), (3, 6), (2, 4), (1, 3), (3, 4), (1, 2), (1, 1), (2, 1)]
I think that that problem is how I am storing the current path (where each node stores its parent node, and then I return the end node and go backwards recursively to get the path). Does anyone have any advice for what I should change? I attached my current code below. Thanks!
What your algorithm is currently doing is trying to find the goal by expending its area around the starting point and finding the best path for every node its visiting.
In a single-goal situation, it works well and you can get the path to this goal.
However how you have adapted it to a multi-goal purpose is that only the stop condition changes (when all goals as been visited once), meaning that you found the shortest path from the start point to each goal but not a single path visiting all nodes.
In the case, you just want the paths from the start point to each goal, just get the path (via parents) from each goal point.
If you really want to implement a pacman-like search, this is NP-Hard problem (see this answer).
As one of the comment proposes, if you have a small list of goals, you can find a solution with brute-force:
Let's say you have 3 goals: A,B,C (which were dots):
%%%%%%%%%%%%%%%%%%%%
%A P %
% %% %% %% %%C%% % %
% %% % B % %
%%%%%%%%%%%%%%%%%%%%
Using your algorithm, you can find the shortest path from P to A, then A to B then B to C. Do the same for other permutations ((P,A,C,B),(P,B,A,C) ...): see itertools.combinations(goals, len(goals))
You can then use your algorithm to find the path from one point to the other:
def A_multiple_goals(maze, start, goals):
paths = []
for itinerary in itertools.combinations(goals, len(goals)):
path = get_path(A_search_multiple(maze, start, itinerary[0])) # First go to first goal from start
for i in range(1 , len(itinerary)): # Then from each goal, goto the next one
path += get_path(A_search_multiple(maze, itinerary[i-1], itinerary[i]))
paths.append(paths)
return min(paths, key=len)
This is a brute-force approach, if you have a lot of goals, you would need a better algorithm based around the Traveling Salesman Problem.