Hytale Modding
Fundamentos do Java

06 — Métodos (Funções)

Aprenda a como organizar e reutilizar o código com métodos.

Os métodos são blocos de código reutilizáveis ​​que executam tarefas específicas. Elas ajudam você a evitar a repetição de código e tornam seus programas mais fáceis de entender.

O que é um método?

Imagine um "método" como uma receita. Defina-o uma vez e então o usa sempre que precisar.

public class Game {
    public static void main(String[] args) {
        greet();        // Chama o método
        greet();        // Chama-o novamente!
    }
    
    // Definição do método
    public static void greet() {
        System.out.println("Bem-vindo(a) ao Hytale!");
    }
}

Estrutura do método

public static void methodName() {
//  ^      ^     ^      ^       ^
//  |      |     |      |       |
// Acessa os parâmetros de nome de retornos estáticos
// Tipo do modificador
    // O código vai aqui
}

Depois, aprenderemos o que significam os métodos public e static. Por enquanto, apenas os use.

Métodos com parâmetros

Os parâmetros permitem passar dados para os métodos:

public static void greetPlayer(String name) {
    System.out.println("Olá, " + name + "!");
}

public static void main(String[] args) {
    greetPlayer("Alice");  // Olá, Alice!
    greetPlayer("Bob");    // Olá, Bob!
}

Múltiplos parâmetros

public static void dealDamage(String target, int damage) {
    System.out.println(target + " recebeu " + damage + " de dano!");
}

public static void main(String[] args) {
    dealDamage("Zumbi", 20);    // Zumbi recebeu 20 de dano!
    dealDamage("Esqueleto", 15);  // Esqueleto recebeu 15 de dano!
}
A ordem dos parâmetros importa

Ao chamar um método, os argumentos devem corresponder à ordem dos parâmetros:

public static void createItem(String name, int quantity, double price) {
    // ...
}

// Correto
createItem("Espada", 1, 50.0);

// Errado — A ordem importa!
createItem(1, "Espada", 50.0);  // Erro!

Métodos com valores de retorno

Os métodos podem enviar dados de volta usando o return:

public static int add(int a, int b) {
    int sum = a + b;
    return sum;
}

public static void main(String[] args) {
    int result = add(5, 3);
    System.out.println(result);  // 8
}

O tipo de retorno deve corresponder ao que você deseja retornar:

  • void — Retorna nada
  • int — Retorna um número inteiro
  • double — Retorna um decimal
  • boolean — Retorna true/false
  • String — Retorna texto
public static String getItemName() {
    return "Espada de Diamante"";
}

public static boolean isPlayerAlive(int health) {
    return health > 0;
}

public static double calculateDamage(int attack, double multiplier) {
    return attack * multiplier;
}
Execução de interrupções de retorno

Quando um método executa o return, ele é encerrado imediatamente. Após o return, o código não será executado!

public static int getValue() {
    return 10;
    System.out.println("Isto nunca será executado!");  // Código inacessível!
}

Exemplos práticos

Sistema de vida

public static void displayHealth(String name, int health, int maxHealth) {
    double percentage = (health * 100.0) / maxHealth;
    System.out.println(name + ": " + health + "/" + maxHealth + 
                      " (" + percentage + "%)");
}

public static void main(String[] args) {
    displayHealth("Jogador", 75, 100);
    displayHealth("Chefe", 450, 500);
}

Calculadora de dano

public static int calculateDamage(int baseAttack, int weaponDamage, boolean isCritical) {
    int totalDamage = baseAttack + weaponDamage;
    
    if (isCritical) {
        totalDamage *= 2;
    }
    
    return totalDamage;
}

public static void main(String[] args) {
    int damage1 = calculateDamage(10, 15, false);  // 25
    int damage2 = calculateDamage(10, 15, true);   // 50
    
    System.out.println("Golpe normal: " + damage1);
    System.out.println("Golpe crítico: " + damage2);
}

Requisitos de nível

public static int getXPForLevel(int level) {
    return level * 100;
}

public static boolean canLevelUp(int currentXP, int currentLevel) {
    int required = getXPForLevel(currentLevel + 1);
    return currentXP >= required;
}

public static void main(String[] args) {
    int playerXP = 450;
    int playerLevel = 4;
    
    if (canLevelUp(playerXP, playerLevel)) {
        System.out.println("Você pode subir de nível");
    } else {
        int needed = getXPForLevel(playerLevel + 1) - playerXP;
        System.out.println("Requer mais" + needed + " de EXP.");
    }
}

Calculadora de distância

public static double calculateDistance(int x1, int y1, int x2, int y2) {
    int dx = x2 - x1;
    int dy = y2 - y1;
    return Math.sqrt(dx * dx + dy * dy);
}

public static boolean isInRange(int x1, int y1, int x2, int y2, double range) {
    double distance = calculateDistance(x1, y1, x2, y2);
    return distance <= range;
}

public static void main(String[] args) {
    // Verifica se o alvo está no alcance
    if (isInRange(0, 0, 5, 5, 10.0)) {
        System.out.println("O alvo está no alcance!");
    }
}

Sobrecarga de método

Você pode ter vários métodos com o mesmo nome, mas com parâmetros diferentes:

public static void displayMessage(String message) {
    System.out.println(message);
}

public static void displayMessage(String message, int times) {
    for (int i = 0; i < times; i++) {
        System.out.println(message);
    }
}

public static void main(String[] args) {
    displayMessage("Olá");           // Chama a primeira versão
    displayMessage("Olá", 3);        // Chama a segunda versão
}
Regras de sobrecarga de métodos

Os métodos são considerados diferentes se eles tiverem:

  • Diferentes números de parâmetros
  • Diferentes tipos de parâmetros
  • Diferentes ordens de parâmetros
public static void test(int a) { }
public static void test(int a, int b) { }        // Contagem diferente
public static void test(double a) { }            // Tipo diferente
public static void test(String a, int b) { }     // Tipos diferentes
public static void test(int a, String b) { }     // Ordem diferente

// Errado — A única diferença é o tipo de retorno 
public static int test(int a) { }

Padrões comuns na criação de mods para o Hytale

Criação de item

public static Item createItem(String name, int durability) {
    Item item = new Item();
    item.setName(name);
    item.setDurability(durability);
    return item;
}

public static Item createSword() {
    return createItem("Espada", 100);
}

public static Item createPickaxe() {
    return createItem("Picareta", 150);
}

Validação do posicionamento de blocos

public static boolean canPlaceBlock(int x, int y, int z) {
    // Verifica se a posição é válida
    if (y < 0 || y > 255) {
        return false;
    }
    
    // Verifica se o bloco já existe
    if (isBlockAt(x, y, z)) {
        return false;
    }
    
    return true;
}

public static void placeBlock(int x, int y, int z, String type) {
    if (canPlaceBlock(x, y, z)) {
        // Coloca o  bloco
        System.out.println("O bloco " + type + " foi colocado em: " + x + ", " + y + ", " + z + "");
    } else {
        // Se não for possível colocar o bloco, esta mensagem é mostrada
        System.out.println("Não é possível colocar blocos!");
    }
}

Verificações de atributos do jogador

public static boolean isLowHealth(int health, int maxHealth) {
    return (health * 100.0 / maxHealth) < 25;
}

public static String getHealthStatus(int health, int maxHealth) {
    double percentage = (health * 100.0) / maxHealth;
    
    if (percentage >= 75) {
        return "Saudável";
    } else if (percentage >= 50) {
        return "Ferido";
    } else if (percentage >= 25) {
        return "Crítico";
    } else {
        return "À beira da morte";
    }
}

Boas práticas

Nomeação de método

Use os nomes descritivos baseados em verbos que expliquem o que o método faz:

// Bom
public static void calculateDamage() { }
public static boolean isPlayerAlive() { }
public static String getItemName() { }
public static void displayInventory() { }

// Ruim
public static void dmg() { }        // Muito curto
public static void method1() { }    //o é descritivo
public static void stuff() { }      // Muito vago

Exercícios práticos

  1. Conversor de temperatura: Digite os métodos para converter:

    • Celsius para Fahrenheit: (C × 9/5) + 32
    • Fahrenheit para Celsius: (F - 32) × 5/9
  2. Calculadora de circunferência: Crie métodos que calculem:

    • Área: π × raio²
    • Circunferência: 2 × π × raio
    • Use Math.PI para π
  3. Durabilidade do item: Digite estes métodos:

    • damageItem(int current, int damage) — retorna uma nova durabilidade
    • isBroken(int durability) — retorna verdadeiro se a durabilidade for menor ou igual a 0
    • repairItem(int current, int max) — retorna a durabilidade máxima
  4. Validador de senha: Crie um método que verifique se uma senha é válida:

    • Com pelo menos 8 caracteres
    • Tenha pelo menos um número
    • Retorna true se for válido, e false se não for

Erros comuns

// Errado — Esquecendo a instrução de retorno
public static int getValue() {
    int x = 10;
    // Esqueceu de retornar!
} !

// Correto
public static int getValue() {
    int x = 10;
    return x;
}

// Errado — Tipo de retorno incorreto
public static int getText() {
    return "Olá";  // Erro! Deve retornar int, não String
}

// Correto
public static String getText() {
    return "Olá";
}

// Errado — Não chamar o método
public static void main(String[] args) {
    greet;  // Erro! Falta os parênteses ()
}

// Correto
public static void main(String[] args) {
    greet();
}