Skip to content

tiago-rods/BattleShip-Assembly

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 

Repository files navigation

BattleShip-Assembly

Trabalho Final de Organização de Sistemas Este projeto consiste na implementação de uma versão simplificada do clássico jogo "Batalha Naval", desenvolvida inteiramente em linguagem Assembly x86. O jogo é projetado para um único jogador, onde o usuário enfrenta um adversário controlado pelo computador. O objetivo principal é afundar todos os navios inimigos antes de esgotar o limite de 50 tiros disponíveis.A escolha da linguagem Assembly x86 para o desenvolvimento deste jogo teve como propósito explorar e aprofundar conhecimentos em programação de baixo nível, manipulação direta de memória e interações com o sistema operacional através de interrupções de BIOS e DOS. O projeto visa demonstrar a capacidade de criar uma aplicação interativa e funcional utilizando recursos fundamentais da arquitetura x86.1.2. Como Funciona: o jogo é disputado em um tabuleiro virtual de 10x10, que é exibido ao jogador como uma seção interativa dentro de uma matriz maior de 13x16 caracteres. No início de cada partida, o computador gera aleatoriamente a posição dos navios inimigos no tabuleiro. O jogador, então, tem a tarefa de adivinhar as coordenadas dos navios, inserindo um número de linha e uma letra de coluna para realizar um ataque.Os resultados dos ataques são indicados visualmente no tabuleiro:

Um acerto (Hit) é representado pelo caractere '■' (código ASCII 16h). Um erro (Miss) é representado pelo caractere '≈' (código ASCII 0F7h).

O jogador possui um limite de 50 tiros para afundar todos os navios. A vitória é alcançada quando todos os navios inimigos são afundados antes que os tiros se esgotem. A derrota ocorre se o jogador ficar sem tiros antes de afundar todos os navios. Ao final de cada partida, o jogador tem a opção de jogar novamente.1.3. Funcionalidades PrincipaisO jogo incorpora diversas funcionalidades essenciais para garantir uma experiência de usuário completa e robusta:

Geração Aleatória do Tabuleiro: Posicionamento dos navios do computador de forma imprevisível a cada nova partida. Validação de Entrada: Verificação das coordenadas inseridas pelo jogador para garantir que estejam dentro dos limites do tabuleiro. Detecção de Acerto/Erro: Lógica para determinar se um tiro atingiu ou errou um navio. Rastreamento de Navios: Monitoramento do estado de cada navio (partes atingidas, navio afundado). Contador de Tiros Restantes: Exibição em tempo real do número de tiros que o jogador ainda possui. Gerenciamento do Estado do Jogo: Controle do fluxo do jogo, incluindo início, progresso, vitória/derrota e reinício. Interface de Usuário Colorida: Utilização de cores para melhorar a legibilidade e a experiência visual do jogador. Controles de Teclado: Interação principal via teclado, com a tecla ESC para sair do jogo a qualquer momento. 1.4. Componentes TécnicosO projeto faz uso extensivo de macros e procedimentos para modularizar o código e facilitar a manutenção e compreensão. Abaixo estão listados os principais componentes:1.4.1. Macros push_all / pop_all: Macros para salvar e restaurar o estado dos registradores, garantindo a integridade do contexto durante chamadas de procedimentos. clear_screen: Macro para limpar a tela do console, proporcionando uma interface limpa a cada nova exibição. print_string / print_number: Macros para exibir cadeias de caracteres e números na tela, respectivamente. move_cursor: Macro para posicionar o cursor em coordenadas específicas (linha, coluna) na tela. input_no_echo: Macro para capturar a entrada do usuário sem exibir o caractere digitado no console. change_string_color: Macro para alterar a cor do texto a ser exibido. tab: Macro para inserir um caractere de tabulação, útil para formatação. 1.4.2. Procedimentos display_initial_screen: Exibe a tela de título e introdução do jogo. show_rules_screen: Apresenta as regras do jogo ao usuário. display_matrix: Renderiza o tabuleiro de jogo na tela, incluindo os acertos e erros. generate_random_numbers: Gera números pseudoaleatórios para o posicionamento dos navios. get_coordinate: Obtém e valida as coordenadas de ataque inseridas pelo jogador. generate_random_board: Preenche o tabuleiro com os navios do computador em posições aleatórias. update_attack: Processa o ataque do jogador, atualiza o tabuleiro e o estado dos navios. display_remaining_ships: Exibe a quantidade de navios restantes a serem afundados. check_sunk_ships: Verifica se algum navio foi completamente afundado após um ataque. check_game_over: Determina se as condições de vitória ou derrota foram atingidas. change_string_color: Procedimento para gerenciar a mudança de cores na interface.

Para detalhes completos sobre a implementação de cada macro e procedimento, consulte o código-fonte no repositório GitHub.1.5. Matérias Avançadas UtilizadasO projeto faz uso de interrupções de sistema para funcionalidades avançadas, demonstrando a interação direta com o hardware e o sistema operacional:

INT 1Ah (Serviços de Tempo): Utilizada para obter o tempo do sistema, que serve como semente para a geração de números pseudoaleatórios. Especificamente, o projeto utiliza os "ticks" do sistema (contagem de pulsos do timer) módulo 10 para gerar uma semente dinâmica. INT 10h (Serviços de Vídeo): Essencial para a manipulação da interface gráfica em modo texto. Esta interrupção é empregada para:

Posicionamento do cursor na tela (move_cursor).
Inserção de tabulações para formatação (tab).
Alteração das cores de fundo e foreground do texto (change_string_color).

1.6. Como JogarSiga os passos abaixo para desfrutar do jogo Batalha Naval:

Pressione qualquer tecla para pular a tela de título e iniciar o jogo. Leia atentamente a tela de regras para entender a dinâmica do jogo. Observe o tabuleiro principal do jogo:

Você terá 50 tiros disponíveis.
Existem 6 navios a serem afundados.
A qualquer momento, você pode pressionar a tecla ESC para sair do jogo.

Para atacar, primeiro selecione o número da linha e, em seguida, a letra da coluna. Posições inválidas (fora do tabuleiro ou já atacadas) não serão contabilizadas contra o seu limite de tiros. Fique atento às notificações de navios afundados. Continue jogando até que você vença (afundando todos os navios) ou perca (esgotando os tiros). Ao final da partida, escolha 'S' ou 's' para jogar novamente, ou 'N' ou 'n' para sair. 1.7. Autores Artur Yano Contarelli (RA: 24014303) Rafael Martiniano Nogueira Filho (RA: 24008538) Tiago Alves Rodrigues (RA: 24001623) 1.8. ReferênciasEste projeto foi desenvolvido com base nos seguintes recursos e materiais de referência:

Intel Corporation. Intel 64 and IA-32 Architectures Software Developer's Manuals. Disponível em: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html Microsoft Corporation. MS-DOS Programmer's Reference. Ray, Duncan. Advanced MS-DOS Programming. Microsoft Press, 1988. Peter Norton. The Peter Norton Programmer's Guide to the IBM PC & PS/2. Microsoft Press, 1989. Kip Irvine. Assembly Language for Intel-Based Computers. Pearson, 2020. TutorialsPoint. Assembly Programming. Disponível em: https://www.tutorialspoint.com/assembly_programming/index.htm 1.9. Nota sobre IAEste projeto utilizou assistência de inteligência artificial exclusivamente para o desenvolvimento de lógica e resolução de problemas. Nenhuma parte do código foi escrita diretamente por ferramentas de IA. A IA foi empregada como uma ferramenta de apoio para refinar algoritmos, otimizar estruturas e auxiliar na depuração, sempre sob a supervisão e controle dos desenvolvedores humanos.1.10. Estrutura do RepositórioO repositório do projeto está organizado para facilitar a navegação e o entendimento:

Código Fonte: Contém todos os arquivos .ASM com procedimentos bem comentados para clareza. Documentação Detalhada: Inclui este README e outros documentos explicativos sobre o design e a implementação. Capturas de Tela e Exemplos de UI: Imagens que demonstram a interface do usuário e o gameplay. Documentação Completa de Macros e Procedimentos: Arquivos adicionais que descrevem em profundidade a funcionalidade de cada componente técnico. 2. README - Battleship Game Assembly x86 Project (English)2.1. About the ProjectThis project is an implementation of a simplified version of the classic "Battleship" game, developed entirely in x86 Assembly language. The game is designed for a single player, where the user faces a computer-controlled opponent. The main objective is to sink all enemy ships before running out of the 50 available shots.The choice of x86 Assembly language for this game's development aimed to explore and deepen knowledge in low-level programming, direct memory manipulation, and interactions with the operating system through BIOS and DOS interrupts. The project demonstrates the capability to create an interactive and functional application using fundamental x86 architecture resources.2.2. How it WorksThe game is played on a virtual 10x10 board, displayed to the player as an interactive section within a larger 13x16 character matrix. At the start of each game, the computer randomly generates the positions of enemy ships on the board. The player then has the task of guessing the ships' coordinates by entering a row number and a column letter to launch an attack.Attack results are visually indicated on the board:

A hit is represented by the character '■' (ASCII code 16h). A miss is represented by the character '≈' (ASCII code 0F7h).

The player has a limit of 50 shots to sink all ships. Victory is achieved when all enemy ships are sunk before the shots run out. Defeat occurs if the player runs out of shots before sinking all ships. At the end of each game, the player has the option to replay.2.3. Key FeaturesThe game incorporates several essential features to ensure a complete and robust user experience:

Random Board Generation: Unpredictable positioning of computer ships for each new game. Input Validation: Verification of player-entered coordinates to ensure they are within board limits. Hit/Miss Detection: Logic to determine if a shot hit or missed a ship. Ship Tracking: Monitoring the state of each ship (hit parts, sunk ship). Remaining Shots Counter: Real-time display of the number of shots the player still has. Game State Management: Control of game flow, including start, progress, win/loss, and restart. Color-Coded UI: Use of colors to improve readability and the player's visual experience. Keyboard Controls: Primary interaction via keyboard, with the ESC key to quit the game at any time. 2.4. Technical ComponentsThe project makes extensive use of macros and procedures to modularize the code and facilitate maintenance and understanding. The main components are listed below:2.4.1. Macros push_all / pop_all: Macros to save and restore register states, ensuring context integrity during procedure calls. clear_screen: Macro to clear the console screen, providing a clean interface for each new display. print_string / print_number: Macros to display character strings and numbers on the screen, respectively. move_cursor: Macro to position the cursor at specific coordinates (row, column) on the screen. input_no_echo: Macro to capture user input without displaying the typed character on the console. change_string_color: Macro to change the color of the text to be displayed. tab: Macro to insert a tab character, useful for formatting. 2.4.2. Procedures display_initial_screen: Displays the game's title and introduction screen. show_rules_screen: Presents the game rules to the user. display_matrix: Renders the game board on the screen, including hits and misses. generate_random_numbers: Generates pseudo-random numbers for ship positioning. get_coordinate: Obtains and validates attack coordinates entered by the player. generate_random_board: Populates the board with computer ships in random positions. update_attack: Processes the player's attack, updates the board, and ship states. display_remaining_ships: Shows the number of remaining ships to be sunk. check_sunk_ships: Checks if any ship has been completely sunk after an attack. check_game_over: Determines if win or loss conditions have been met. change_string_color: Procedure to manage color changes in the interface.

For full details on the implementation of each macro and procedure, please refer to the source code in the GitHub repository.2.5. Advanced Topics UsedThe project makes use of system interrupts for advanced functionalities, demonstrating direct interaction with hardware and the operating system:

INT 1Ah (Time Services): Used to obtain the system time, which serves as a seed for pseudo-random number generation. Specifically, the project uses system "ticks" (timer pulse count) modulo 10 to generate a dynamic seed. INT 10h (Video Services): Essential for text-mode graphical interface manipulation. This interrupt is employed for:

Cursor positioning on the screen (move_cursor).
Insertion of tabs for formatting (tab).
Changing foreground and background text colors (change_string_color).

2.6. How to PlayFollow the steps below to enjoy the Battleship game:

Press any key to skip the title screen and start the game. Carefully read the rules screen to understand the game dynamics. Observe the main game board:

You will have 50 shots available.
There are 6 ships to sink.
At any time, you can press the ESC key to quit the game.

To attack, first select the row number, then the column letter. Invalid positions (off-board or already attacked) will not count against your shot limit. Watch for ship sunk notifications. Continue playing until you win (by sinking all ships) or lose (by running out of shots). At the end of the game, choose 'S' or 's' to replay, or 'N' or 'n' to exit. 2.7. Authors Artur Yano Contarelli Rafael Martiniano Nogueira Filho Tiago Alves Rodrigues 2.8. ReferencesThis project was developed based on the following resources and reference materials:

Intel Corporation. Intel 64 and IA-32 Architectures Software Developer's Manuals. Available at: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html Microsoft Corporation. MS-DOS Programmer's Reference. Ray, Duncan. Advanced MS-DOS Programming. Microsoft Press, 1988. Peter Norton. The Peter Norton Programmer's Guide to the IBM PC & PS/2. Microsoft Press, 1989. Kip Irvine. Assembly Language for Intel-Based Computers. Pearson, 2020. TutorialsPoint. Assembly Programming. Available at: https://www.tutorialspoint.com/assembly_programming/index.htm 2.9. AI NoteThis project utilized AI assistance exclusively for logic development and problem-solving. No code was directly written by AI tools. AI was employed as a support tool to refine algorithms, optimize structures, and assist in debugging, always under the supervision and control of human developers.2.10. Repository StructureThe project repository is organized to facilitate navigation and understanding:

Source Code: Contains all .ASM files with well-commented procedures for clarity. Detailed Documentation: Includes this README and other explanatory documents about the design and implementation. Game Screenshots and UI Examples: Images demonstrating the user interface and gameplay. Full Macros and Procedures Documentation: Additional files that describe in depth the functionality of each technical component.

About

Trabalho Final de Organização de Sistemas

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors