Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Zombie class
- class Zombie:
- def __init__(self, health):
- self.health = health
- def remove_health(self, amount):
- if amount < self.health:
- self.health -= amount
- return 0
- else:
- rest = amount - self.health
- self.health = 0
- return rest
- # Shooter class
- class Shooter:
- def __init__(self, kind):
- self.kind = "N" if kind.isnumeric() else "S"
- self.shots = int(kind) if kind.isnumeric() else 1
- # helper function to draw the grid
- def draw_grid(grid):
- for row in grid:
- line = ""
- for item in row:
- if isinstance(item, Shooter):
- line += item.kind + " "
- elif isinstance(item, Zombie):
- line += str(item.health) + ("" if item.health > 9 else " ")
- else:
- line += ". "
- print(line)
- print("--------------")
- print()
- # main game function
- def plants_and_zombies(lawn, zombies):
- grid = []
- row_len = len(lawn[0]) - 1
- running = True
- move = 0
- # Place the Shooter-Objects in the Grid
- for row in range(len(lawn)):
- new_row = []
- for c in lawn[row]:
- if c == ' ':
- new_row.append(0)
- else:
- new_row.append(Shooter(c))
- grid.append(new_row)
- while running: # main game loop
- # Move Zombies
- for i, row in enumerate(grid):
- for j, item in enumerate(row):
- if isinstance(item, Zombie):
- grid[i][j - 1] = item
- grid[i][j] = 0
- # Spawn Zombies
- for i, row, hp in zombies:
- if i == move:
- grid[row][row_len] = Zombie(hp)
- # The number shooters shoot in a acluster for every row
- for r, row in enumerate(grid):
- shots_in_row = 0
- for item in row:
- if isinstance(item, Shooter):
- if item.kind == "N":
- shots_in_row += item.shots
- for c, item in enumerate(row):
- if isinstance(item, Zombie):
- rest = item.remove_health(shots_in_row)
- if item.health <= 0:
- grid[r][c] = 0
- if rest > 0:
- shots_in_row = rest
- else:
- break
- # The super shooters shoot from rigth to left and top to bottom
- for col in range(len(grid[0]) - 1, -1, -1):
- for row in range(len(grid)):
- if isinstance(grid[row][col], Shooter):
- if grid[row][col].kind == "S":
- for dr, dc in [(1, 1), (-1, 1), (0, 1)]:
- if row + dr > len(grid) or row + dr < 0 or col + dc > len(grid[0]):
- continue
- nrow, ncol = row + dr, col + dc
- while nrow >= 0 and nrow < len(grid) and ncol < len(grid[0]):
- if isinstance(grid[nrow][ncol], Zombie):
- grid[nrow][ncol].remove_health(1)
- if grid[nrow][ncol].health <= 0:
- grid[nrow][ncol] = 0
- break
- nrow += dr
- ncol += dc
- # increase the move counter an check if the game is over
- # draw_grid(grid) helper function
- move += 1
- zombie_count = 0
- for row in grid:
- for item in row:
- if isinstance(item, Zombie):
- zombie_count += 1
- if zombie_count <= 0:
- print("None")
- return None
- for i in range(len(grid)):
- if isinstance(grid[i][0], Zombie):
- print(move)
- return move
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement