Вступ до Python
На цьому уроці розберемо основи мови програмування Python, її переваги та сфери застосування. Також розглянемо середовище розробки, в якому працюватимемо, та розглянемо вбудовані типи даних.
Код і результати
Опублікована версія після Merge. Результати збережені автором; код на цій сторінці не запускається.
implementation.py · v1
class TimeLoopEchoGame:
def __init__(self, grid_size: int, max_turns: int):
self.grid_size = grid_size
self.max_turns = max_turns
self.player_pos = (0, 0)
self.exit_pos = (grid_size - 1, grid_size - 1)
self.history = set() # Множина пройдених координат (відлуння)
self.current_turn = 0
self.game_over = False
self.won = False
def move(self, direction: str) -> str:
if self.game_over:
return "Game Over"
# Додаємо поточну позицію до історії (відлуння) перед здійсненням кроку
self.history.add(self.player_pos)
x, y = self.player_pos
if direction == "w":
y = y - 1
elif direction == "s":
y = y + 1
elif direction == "a":
x = x - 1
elif direction == "d":
x = x + 1
else:
return "Invalid Direction"
assert 0 <= x < self.grid_size and 0 <= y < self.grid_size, "Рух за межі таблиці заборонений"
self.player_pos = (x, y)
self.current_turn += 1
# Перевірка умови перемоги
if self.player_pos == self.exit_pos:
self.won = True
self.game_over = True
return "Won"
# Перевірка зіткнення з власним відлунням
if self.player_pos in self.history:
self.game_over = True
return "Collided with Echo"
# Перевірка вичерпання ходів
if self.current_turn >= self.max_turns:
self.game_over = True
return "Out of Turns"
return "Continue"
def print_board(self):
"""Візуалізує ігрове поле в текстовому вигляді."""
for y in range(self.grid_size):
row = []
for x in range(self.grid_size):
pos = (x, y)
if pos == self.player_pos:
row.append("@") # Гравець
elif pos == self.exit_pos:
row.append("E") # Вихід
elif pos in self.history:
row.append("#") # Відлуння (не можна наступати)
else:
row.append(".") # Пусто
print(" ".join(row))
print(f"Turn: {self.current_turn}/{self.max_turns}\n")
game = TimeLoopEchoGame(3,10)
while game.game_over != True:
game.print_board()
print(game.move(input()))Рев’ю спільноти
Appoved. Гарна робота.
