0% found this document useful (0 votes)
4 views14 pages

Java Database Authentication System

java

Uploaded by

alifrasyidf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

Java Database Authentication System

java

Uploaded by

alifrasyidf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Src

Com

Auth

Config

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@SuppressWarnings("CallToPrintStackTrace")
public class DB {
private static final String JDBC_DRIVER =
"[Link]";
private static final String DB_URL =
"jdbc:mysql://localhost:3306/gamedb";
private static final String USER = "root";
private static final String PASSWORD = "spensa92";

static {
try {
[Link](JDBC_DRIVER); // Load driver saat aplikasi
dijalankan
} catch (ClassNotFoundException e) {
[Link]("Driver MySQL tidak ditemukan!");
[Link]();
}
}

// Membuat koneksi ke database


private static Connection getConnection() throws
SQLException {
return [Link](DB_URL, USER,
PASSWORD);
}

// Mencari akun berdasarkan email


public static int cariData(String eml, String pwd) {
String query = "SELECT ID FROM akun WHERE email = ?";
try (Connection conn = getConnection();
PreparedStatement stmt =
[Link](query)) {
[Link](1, eml);

try (ResultSet rs = [Link]()) {


if ([Link]()) {
return [Link]("ID");
}
}
} catch (SQLException e) {
[Link]();
}
return 0; // Jika tidak ditemukan, kembalikan 0
}

// Login akun
public static String authAkun(int id, String eml, String
password) {
String query = "SELECT EMAIL, PASSWORD FROM akun
WHERE ID = ?";
try (Connection conn = getConnection();
PreparedStatement stmt =
[Link](query)) {

[Link](1, id);

try (ResultSet rs = [Link]()) {


if ([Link]()) {
String dbEmail = [Link]("EMAIL");
String dbPassword = [Link]("PASSWORD");

if ([Link](eml) &&
[Link](password)) {
return "Login Success";
}
}
}
} catch (SQLException e) {
[Link]();
}
return "Incorrect email or password";
}

// Register akun
public static boolean register(String email, String password) {
String query = "INSERT INTO akun (EMAIL, PASSWORD)
VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt =
[Link](query)) {

[Link](1, email);
[Link](2, password);

int rowsAffected = [Link]();


return rowsAffected > 0; // Return true jika berhasil
menambahkan data
} catch (SQLException e) {
[Link]();
}
return false; // Jika gagal
}
}
View

[Link]

package [Link];

import [Link];
import [Link];
public class LoginExtendSuperV extends SuperV {

public LoginExtendSuperV (){


}

public void viewLogin(){


String msg = "";
do {

view();
String email = getEmail();
String password = getPassword();
int a = [Link](email, password);
if (a > 0){
msg = [Link](a, email, password);
[Link](msg);
}else{
[Link]("Account is not registered yet");
}
} while (![Link]("Login Success"));
//langsung keprogram
Game game = new Game();

[Link]();
}
}

LR_View.java

package [Link];

import [Link];

public class LR_View {


public static void view(){

LoginExtendSuperV login = new LoginExtendSuperV();


RegisterExtendSuperV register = new
RegisterExtendSuperV();
try (Scanner scanner = new Scanner([Link])) {
int option;
do{
[Link](
"""
\n=== Welcome to TextBased-RPG Game
===
1. Login
2. Register
3. Exit
Choose your option[1/2/3]: """);

option = [Link]();
switch (option) {
case 1 -> [Link]();
case 2 -> [Link]();
case 3 -> [Link]("Goodbye!");
default -> [Link]("Invalid option. Please
choose again.");
}
} while (option !=3);
}
}
}

[Link]

package [Link];

import [Link];

public class RegisterExtendSuperV extends SuperV {


@SuppressWarnings("static-access")
public void viewRegister(){

view();
String email = getEmail();
String password = getPassword();
DB register = new DB();
int a = [Link](email, password);
if(a > 0){
[Link]("Email already exsist!!");

}else{
if ([Link](email, password)) {
[Link]("Account successfully
registered");
} else{
[Link]("Failed to register");
}
}
}

SuperV

package [Link];

import [Link];

public class SuperV {

private String email;


private static String password;
private static final Scanner scanner = new Scanner([Link]);

public SuperV(){
// [Link] = email;
// [Link] = password;
}

public void setEmail(){


[Link] = [Link]();
}

public void setPassword(){


password = [Link]();
}
public String getEmail(){
return email;
}

public String getPassword(){


return password;
}

public void view(){


[Link](
"""
\nPlease Enter Your Email!!
Email: """);
setEmail();

[Link](
"""
\nPlease Enter Your Password!!
Password: """);
setPassword();
}

}
Main
[Link]

package [Link];
class Armor{
private int defencePower;
private String name;

Armor(String name, int defencePower){


[Link] = name;
[Link] = defencePower;
}

public int getDefencePower(){


return defencePower;
}

public void setDefencePower(int defencePower){


[Link] = defencePower;
}

public String getName(){


return name;
}
public void setName(String name){
[Link] = name;
}

void display(){
[Link]("Armor: " + getName() + ", Def: " +
getDefencePower());
}
}

[Link]

package [Link];
class Character{
private String name;
private int health;
private int attackPower;

public Character(String name, int health, int attackPower){


[Link] = name;
[Link] = health;
[Link] = attackPower;
}

public String getName(){


return name;
}

public void setName(String name){


[Link] = name;
}

public int getHealth(){


return health;
}

public void setHealth(int health){


[Link] = health;
}

public int getAttackPower(){


return attackPower;
}

public void setAttackPower(int attackPower){


[Link] = attackPower;
}
public boolean isAlive(){
return health > 0;
}

public void attack(Character opponent){


[Link](getName() + " attack " +
[Link]() + " with damage " + getAttackPower());
[Link](getAttackPower());
}

public void takeDamage(int damage){


setHealth(getHealth() - damage);
[Link](getName() + " suffered damage " +
damage + "\n");

if(getHealth() <= 0){


[Link](getName() + " is dead");
}
}

public void displayStatus(){


[Link](getName() + " - Health " + getHealth());
}
}

[Link]
package [Link];
import [Link];

public class Game{


private Player player;
private Monster monster;
private Armor armor;
private Weapon weapon;
private final Scanner scanner;

public Game(){
scanner = new Scanner([Link]);
}

public void start(){


[Link]("\n==== Welcome to Text-based RPG!
====\n");
[Link]("Enter username: ");
String username = [Link]();
player = new Player(username);
choseWeapon();
choseArmor();
[Link]();
[Link]("\n*** Monster appear! ***");
[Link]("Goblin !!!");
[Link]("Defeat the monster!\n");
monster = new Monster("Goblin");

battle();
}

private void battle(){


while ([Link]() && [Link]()){
[Link]();
[Link]();

[Link]("\nWhat do you want to do?");


[Link]("1. Attack");
[Link]("2. Heal");
[Link]("3. Run");
[Link](">> ");
int choice = [Link]();
[Link]("");
switch(choice){
case 1 -> [Link](monster);
case 2 -> [Link]();
case 3 -> {
[Link]("You run from the monster!");
[Link]("The monster is chasing
you!!\n");
}
default -> {
[Link]("Invalid choice!");
continue;
}
}
if([Link]()){
[Link](player);
}
}

if([Link]()){
[Link]("\nYou win!\n");
}else{
[Link]("\nYou lose!\n");
}
}

private void choseWeapon(){


Weapon weapon1 = new Weapon("Sword", 20);
Weapon weapon2 = new Weapon("Spear", 20);
Weapon weapon3 = new Weapon("Sickle", 20);
[Link]("\nPlease Choose a weapon !");
[Link]("1. Sword");
[Link]("2. Spear");
[Link]("3. Sickle");
[Link](">> ");
int choiceWeapon = [Link]();
switch(choiceWeapon){
case 1 -> {
weapon = weapon1;
[Link](weapon);
}
case 2 -> {
weapon = weapon2;
[Link](weapon);
}
case 3 -> {
weapon = weapon3;
[Link](weapon);
}
default -> {
[Link]("Invalid choice");
choseWeapon();
}
}
}

private void choseArmor(){


Armor armor1 = new Armor("Steel Armor", 10);
Armor armor2 = new Armor("Iron Armor", 10);
[Link]("\nPlease chose a Armor!");
[Link]("1. Steel Armor");
[Link]("2. Iron Armor");
[Link](">> ");
int choiceArmor = [Link]();
switch(choiceArmor){
case 1 -> {
armor = armor1;
[Link](armor);
}
case 2 -> {
armor = armor2;
[Link](armor);
}
default -> {
[Link]("Invalid choice");
choseArmor();
}
}
}
}

[Link]

package [Link];
class Monster extends Character{
public Monster(String name){
super(name, 90, 20);
}

@Override
public void attack(Character opponent){
[Link](getName() + " viciously attacks " +
[Link]());
[Link](opponent);
}

@Override
public void takeDamage(int damage){
[Link](getName() + " roars in pain!");
[Link](damage);
}
}

[Link]
package [Link];
class Player extends Character{
private int healAmount;
Weapon weapon;
Armor armor;

public Player(String name){


super(name, 100, 10);
[Link] = 15;
}

public void setHealAmount(int healAmount){


[Link] = healAmount;
}

public int getHealAmount(){


return healAmount;
}
public void heal(){
[Link](getName() + " heal him self. ");
setHealth(getHealth() + getHealAmount());
if(getHealth() > 100){
setHealth(100);
}
[Link]("Current Healt: " + getHealth() + "\n");
}

void equipWeapon(Weapon weapon){


[Link] = weapon;
[Link]([Link]() + 10);
}

void equipArmor(Armor armor){


[Link] = armor;
}

void display(){
[Link]("\n+++++++++++++++++++++++++++");
[Link]("Name: " + getName());
if(getHealth() <= 0){
[Link]("(Player dead!!!)");
}else{
[Link]("HP: " + getHealth());
[Link]();
[Link]();
[Link]("Total attack: " + getAttackPower());
}
[Link]("+++++++++++++++++++++++++++");
}

@Override
public void attack(Character opponent){
[Link](getName() + " performs a powerful
strike on " + [Link]());
[Link](opponent);
}

@Override
public void takeDamage(int damage){
if(armor != null){
int reduceDamage = damage - [Link]();
if(reduceDamage < 0){
reduceDamage = 0;
}
[Link](getName() + "'s armor reduces the
damage " + [Link]());
[Link](reduceDamage);
}else{
[Link](damage);
}
}
}

[Link]
package [Link];
class Weapon{
private String name;
private int damage;

Weapon(String name, int damage){


[Link] = name;
[Link] = damage;
}

public String getName(){


return name;
}

public void setName(String name){


[Link] = name;
}

public int getDamage(){


return damage;
}

public void setDamage(int damage){


[Link] = damage;
}

void display(){
[Link]("Weapon: " + getName() + ", Damage: "
+ getDamage());
}

[Link]

import [Link].LR_View;

public class App {


@SuppressWarnings("static-access")
public static void main(String[] args){

LR_View initialDisplay = new LR_View();


[Link]();
// [Link]();

// Game game = new Game();


// [Link]();
// [Link]("===== code by: Kelompok 1 TID 23=====");
}
}

Common questions

Powered by AI

When registering a new user, the application first calls 'cariData' to check if the email already exists in the database. If the email is found, a message 'Email already exsist!!' is displayed. If not, the 'register' method is invoked, which attempts to insert the email and password into the database. If insertion is successful, 'Account successfully registered' is printed, otherwise 'Failed to register' is displayed .

The game application deals with invalid user input through a switch-case construction during action choices in a battle. If a non-existent action number is entered, the default case triggers, displaying 'Invalid choice!' and prompts the user again for action input. The application does not proceed until a valid input is provided. This mechanism ensures the game loop continues correctly without executing invalid options, maintaining gameplay flow .

The login process verifies user credentials by first checking the email with 'cariData' method that executes a SQL query to find the user ID. If the ID is found, the 'authAkun' method is called, executing another SQL query to fetch the stored email and password for that user ID. It then compares the provided email and password with the retrieved values. If they match, 'Login Success' is returned; if not, it returns 'Incorrect email or password'. If no ID is found in the first query, 'Account is not registered yet' is printed .

The database connection initialization in the class 'DB' ensures the driver is available by using the static block to load the MySQL JDBC driver with 'Class.forName(JDBC_DRIVER)'. If this process fails, a 'ClassNotFoundException' is caught and a message 'Driver MySQL tidak ditemukan!' is printed along with the stack trace .

During a battle, the game handles player actions through a loop where the player can choose to attack, heal, or run via a console input. If the player attacks, they deal damage to the monster; if they heal, their health is increased; if they run, a message indicates the monster is chasing. After each player action, if the monster is still alive, it attacks the player. Victory is declared if the monster is defeated, or defeat if the player is killed. This design follows the Command Pattern, where player choices (commands) result in different methods being executed .

Polymorphism is utilized within the game through method overrides in subclasses of 'Character', specifically 'Player' and 'Monster'. Both classes override methods 'attack' and 'takeDamage', providing unique behaviors suited to each character type, such as 'Player' executing a 'powerful strike' and 'Monster' executing a 'vicious attack'. This polymorphism enables flexible interaction handling, where the same method call can produce different effects depending on the actual object type, enhancing extensibility and maintainability in character behavior implementation .

The application checks the user passwords by retrieving the stored password corresponding to the provided email using a SQL SELECT query. During the login attempt, after the application verifies the email and retrieves the associated password from the database, it directly compares this stored password with the one the user inputs using 'equals' method. This approach ensures that the actual stored password string must exactly match the input password string for a successful login attempt .

The 'SuperV' class facilitates user interaction by providing methods to retrieve user-input email and password via console input. It sets these inputs in instance variables and supports both login and registration operations by serving as a common superclass, from which both 'LoginExtendSuperV' and 'RegisterExtendSuperV' inherit. This design choice supports reusability by avoiding code duplication for input handling between these processes .

The choice of weapons and armor reflects user experience design by providing straightforward options with clear benefits, such as consistent damage bonuses across weapons and fixed defense values for armor. This simplicity ensures players can easily understand their impact on gameplay, encouraging engagement through accessible decision-making without requiring complex calculations or decisions. Automatically equipping selected items further streamlines the experience, reflecting a design focus on fluidity and player empowerment .

In the RPG game, weapons and armor mechanics enhance player capability. Weapons, when equipped by the player, increase attack power by adding their damage value to the player's base attack power. For example, choosing a weapon like a sword increases the player's attack power by the weapon's damage value plus a bonus. Armor reduces incoming damage during a battle; its 'defencePower' mitigates the damage taken from enemy attacks, which can prevent player death and extend survivability in combat. Thus, equipment choice directly influences battle outcomes .

You might also like