Program HistoriofHelic; uses crt; Type Heroes=record// Тип "Герой"в якому будуть…
- User
Program Histori_of_Helic; uses crt; Type Heroes=record// Тип "Герой"в якому будуть зберігатися дані про героя. Name:string[30];//Ім'я героя X:integer;// Положення героя по X Y:integer;//Положення героя по Y HP:integer; //Життя героя end; Const Size_map=50;//Розмір карти Oll_map=1;//Кількість карт Var //!!!!В різих локаціях, по ідеї різний ромір карт, якщо можна реалізувати різні значення розміру карт - це економить пам'ять Map:array[1..Size_map,1..Size_map,1..Oll_map] of string;// Масив, в якому зерігаються дані про структуру різних карт NPS:array[1..100] of string; //Масив в якому зберігаються персонажі Hero:Heroes; //i:integer;//Для циклу //j:integer;//Для циклу chek:integer;//Вибір пункту меню Type Interfac=class public class procedure Watch_y_s;//Виводить повідомлення про те, що лежить пыд ногами героя Begin if Map[Hero.Y,Hero.X,1]='Трава' then writeln('Під вами зелена трава'); if Map[Hero.Y,Hero.X,1]='Камiнь' then writeln('Під скалисте каміння'); end; class procedure Menu_Map; begin Writeln('z-подивитись пiд ноги;i-відкрити iнвертар;g-переглянути склад вашої групу'); end; end; Procedure Random_map;//Процедура для створення карти var i:integer;//Для циклу j:integer;//Для циклу begin for i:=1 to Size_map do for j:=1 to Size_map do Map[i,j,1]:='Трава';// Цикл заповняє основну карту травою(нехай покищо трава буде по українськи) Map[30,30,1]:='Камiнь';
end; Procedure Show_map;//Процедура виводить карту var x,y:integer;//Для циклу begin if (Hero.X<1)then Hero.X:=1; // if (Hero.X>Size_map-1)then Hero.X:=Size_map-1;//Перевірка, чи не вийшов герой за карту if (Hero.Y<1)then Hero.Y:=1; // if (Hero.Y>Size_map-1)then Hero.Y:=Size_map-1;// for y:=Hero.Y-10 to Hero.Y+10 do begin //Цикл виводит на основну карту елементи for x:=Hero.X-10 to Hero.X+10 do begin if (x<=0) then write(' ');// Відступ від лівого краюif ((y<=Size_map) and (x<=Size_map) and(y>=0) and (x>=0) ) then if ((y=Hero.Y)and(x=Hero.X)) then begin textcolor(red); Write('')//Перевірка, чи на клітинці стоїть герой end else if ((y=Size_map) or (x=Size_map)or (y=0) or (x=0)) then begin textcolor(White);//окреслення кінця карти Write('{EN}'); end else begin if Map[y,x,1]='Трава' then begin textcolor(green); Write('{TR}');// Перевірка, чи знаходиться на даній клітинці трава end; if Map[y,x,1]='Камiнь' then begin textcolor(LightGray); Write('{RR}');// Перевірка, чи знаходиться на даній клітинці каміня end; end; end;
writeln(); end;textcolor(white);
end; Procedure New_game;//Процедура запускаэ нову гру begin Hero.HP:=100; Hero.X:=50; Hero.Y:=50; Random_map;//Створується карта //Show_map;//Карта виводиться на екран end; procedure KeyDown();//Процедура для обробки нажимання клавіш label 01; begin 01: case ReadKey of //Опрацювання натисту клавіші в перемикаці #37 : Hero.X:=Hero.X-1; //Натиснута клавіша "Вліво" #39 : Hero.X:=Hero.X+1; //Натиснута клавіша "Вправо" #38 : Hero.Y:=Hero.Y-1; //Натиснута клавіша "Вверх" #40 : Hero.Y:=Hero.Y+1; //Натиснута клавіша "Вниз" #255,#122,#233,#90: begin //Натиснута клавіша "Я","Z" Interfac.Watch_y_s; goto 01; end; end; //vk_Space: if kSpaceKey=2 then kSpaceKey := 1;
end; Procedure Game_run;//Опрацювання запущеноъ гри Label 01; begin 01:clrscr; Show_map;//Показати карту Interfac.Menu_Map; Writeln('x=',Hero.X,'y=',Hero.Y); KeyDown();//Ввести команду goto 01; end; Begin textcolor(white); writeln('Головне меню'); writeln('1.Нова гра'); writeln('2.Вихiд'); readln(chek); case chek of 1: begin New_game; Game_Run; end; 2:exit; end; end.Rewrite this code in Python.
- Assistant
Sure! Below is the Python version of your Pascal text-based game. This Python implementation uses the
coloramalibrary for colored console output andmsvcrtfor handling keyboard input on Windows. If you're using a Unix-based system, you'll need to adjust the key handling accordingly or use a cross-platform library likecurses.Prerequisites
-
Install
colorama:pip install colorama -
Note on
msvcrt:- The
msvcrtmodule is specific to Windows. If you're using Linux or macOS, consider using thecurseslibrary or other cross-platform alternatives for key handling.
- The
Python Code Implementation
import os import sys import msvcrt from colorama import init, Fore, Style # Initialize colorama init() # Constants SIZE_MAP = 50 # Size of the map OLL_MAP = 1 # Number of maps (currently only one map is implemented) # Define the Hero class class Hero: def __init__(self, name="Hero", x=0, y=0, hp=100): self.name = name # Name of the hero self.x = x # X position of the hero self.y = y # Y position of the hero self.hp = hp # Health points of the hero # Define the Interface class class Interface: @classmethod def watch_y_s(cls, game_map, hero): """ Displays a message based on what is under the hero's feet. """ cell = game_map[hero.y][hero.x][0] if cell == 'Трава': print(Fore.GREEN + 'Під вами зелена трава' + Style.RESET_ALL) elif cell == 'Камiнь': print(Fore.LIGHTBLACK_EX + 'Під скалисте каміння' + Style.RESET_ALL) else: print('Невідома поверхня') @classmethod def menu_map(cls): """ Displays the menu options. """ print('z - Подивитись під ноги | i - Відкрити інвентар | g - Переглянути склад вашої групи') # Function to clear the console screen def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') # Function to create a random map def random_map(game_map): """ Initializes the map with 'Трава' (Grass) and places a 'Камiнь' (Rock) at a specific location. """ for i in range(SIZE_MAP): for j in range(SIZE_MAP): game_map[i][j][0] = 'Трава' # Fill the map with grass # Place a rock at position (30, 30). Adjusted for 0-based indexing. game_map[29][29][0] = 'Камiнь' # Function to display the map centered around the hero def show_map(game_map, hero): """ Displays a 21x21 section of the map centered around the hero. """ # Clamp hero's position to stay within the map boundaries hero.x = max(1, min(hero.x, SIZE_MAP - 2)) hero.y = max(1, min(hero.y, SIZE_MAP - 2)) # Define the viewing window around the hero min_y = hero.y - 10 max_y = hero.y + 10 min_x = hero.x - 10 max_x = hero.x + 10 for y in range(min_y, max_y + 1): for x in range(min_x, max_x + 1): if x < 0 or y < 0: print(' ', end='') # Indentation from the left edge continue if x >= SIZE_MAP or y >= SIZE_MAP: # Out of map bounds print(Fore.WHITE + '{EN}' + Style.RESET_ALL, end='') elif x == hero.x and y == hero.y: # Hero's position print(Fore.RED + '<HH>' + Style.RESET_ALL, end='') else: cell = game_map[y][x][0] if cell == 'Трава': print(Fore.GREEN + '{TR}' + Style.RESET_ALL, end='') elif cell == 'Камiнь': print(Fore.LIGHTBLACK_EX + '{RR}' + Style.RESET_ALL, end='') else: print('{??}', end='') # Unknown cell print() # Newline after each row # Function to initialize a new game def new_game(hero, game_map): """ Sets up a new game by initializing the hero's stats and creating the map. """ hero.hp = 100 hero.x = 49 # Starting X position (50 in Pascal, adjusted for 0-based indexing) hero.y = 49 # Starting Y position (50 in Pascal, adjusted for 0-based indexing) random_map(game_map) # Function to handle key presses def key_down(game_map, hero): """ Handles key presses to move the hero or perform actions. """ while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == b'\xe0': # Special keys (arrows, function keys, etc.) key2 = msvcrt.getch() if key2 == b'K': # Left arrow hero.x -= 1 elif key2 == b'M': # Right arrow hero.x += 1 elif key2 == b'H': # Up arrow hero.y -= 1 elif key2 == b'P': # Down arrow hero.y += 1 else: # Handle other keys if key in [b'z', b'Z', b'\xff', b'\xe9', b'\x90']: Interface.watch_y_s(game_map, hero) break # Exit after handling one key press # Function to run the main game loop def game_run(hero, game_map): """ Main game loop that continuously updates and displays the game state. """ while True: clear_screen() show_map(game_map, hero) print() Interface.menu_map() print(f'Позиція героя: x={hero.x + 1}, y={hero.y + 1}') # +1 to match Pascal's 1-based indexing key_down(game_map, hero) # Main function def main(): """ Entry point of the game. Displays the main menu and handles user selection. """ # Initialize the game map game_map = [[[ ' ' for _ in range(OLL_MAP)] for _ in range(SIZE_MAP)] for _ in range(SIZE_MAP)] NPS = [''] * 100 # Non-Player Characters (not used in current implementation) hero = Hero() while True: clear_screen() print('Головне меню') print('1. Нова гра') print('2. Вихiд') print('Виберіть опцію (1 або 2): ', end='') chek = input() if chek == '1': new_game(hero, game_map) game_run(hero, game_map) elif chek == '2': print('Вихід з гри...') sys.exit() else: print('Невірний вибір. Натисніть будь-яку клавішу, щоб спробувати ще раз...') msvcrt.getch() # Run the game if __name__ == "__main__": main()Explanation of the Python Code
-
Imports and Initialization:
coloramais initialized to handle colored text in the console.msvcrtis used for capturing keyboard inputs on Windows.
-
Classes:
HeroClass: Represents the main character with attributes likename,x,y, andhp.InterfaceClass: Contains class methods to display messages related to the hero's surroundings and the in-game menu.
-
Functions:
clear_screen(): Clears the console screen usingclsfor Windows orclearfor Unix-based systems.random_map(): Initializes the game map by filling it with grass ('Трава') and placing a rock ('Камiнь') at a specific location.show_map(): Displays a 21x21 grid section of the map centered around the hero's current position. It uses colored text to represent different terrain types and the hero.new_game(): Sets up a new game by initializing the hero's position and health, and generating the map.key_down(): Captures and handles key presses for moving the hero or performing actions like looking under the feet.game_run(): The main game loop that continuously updates the game state, displays the map and menu, and processes user input.main(): The entry point of the game that displays the main menu and handles user selections for starting a new game or exiting.
-
Main Loop:
- The
main()function displays the main menu and waits for the user to select an option. If the user selects "1", a new game starts; if "2" is selected, the game exits.
- The
-
Key Handling:
- Arrow keys are used to move the hero around the map.
- Pressing
'z'or'Z'allows the hero to look at what's directly underneath.
Additional Notes
-
Extensibility:
- The current implementation supports only one map (
OLL_MAP = 1). To add more maps with different sizes, you can modify therandom_mapfunction and adjust the map initialization accordingly. - The
NPSarray is defined but not utilized. You can extend the game by adding non-player characters and implementing interactions.
- The current implementation supports only one map (
-
Cross-Platform Compatibility:
- The key handling using
msvcrtis specific to Windows. For cross-platform support, consider using libraries likecursesorkeyboard. However, these may require additional setup and permissions.
- The key handling using
-
Error Handling:
- The current implementation assumes valid inputs in most places. You might want to add more robust error handling and input validation for a production-ready game.
-
Performance:
- For larger maps or more complex game logic, consider optimizing data structures and rendering methods.
Running the Game
-
Ensure you have Python installed on your system (preferably Python 3.6 or later).
-
Install the required library (
colorama) using pip:pip install colorama -
Save the Python code to a file, for example,
histori_of_helic.py. -
Run the game using the command:
python histori_of_helic.py
Use the arrow keys to move the hero around the map. Press
'z'to look at what's under the hero's feet. The main menu allows you to start a new game or exit.Enjoy your game development journey!
-