[mini프로젝트] 사칙연산게임 - 4. 코딩 & 완성

HodooHa·2024년 5월 17일

기획, 설계 모두 완료하고 코딩에 들어갔다.
현재 배우고 있는 JDBC를 바로 적용시켜 오라클과 연결하였다.
내 담당인 상점과 인벤토리 부분만 소개하겠다.

먼저 결과물부터!!

결과물

지난 UI설계도와 비교하였을 때 크게 달라진 부분은 없다.
기획했던대로로 상점, 코인 인벤토리, 아이템 인벤토리 3개의 페이지로 구성하였고, 각 인벤토리에 '홈으로' 버튼을 '상점으로' 버튼으로 변경하였다.

상점 페이지에서 코인, 아이템 인벤토리로 들어갈 수 있다.
구매와 동시에 나의 코인 개수가 변경되며, 보유한 코인 개수가 아이템 가격보다 적을 경우 경고창이 뜨고 구입에 실패한다.


게임에서 획득한 점수를 코인으로 전환할 수 있는데, 전환할 점수를 입력하고 확인버튼을 누르면 전환될 코인 개수가 출력된다.
만약 보유한 점수보다 더 많이 전환하고자하면 경고창이 뜨고 전환에 실패한다.


구매한 후 아이템 인벤토리에 들어가면 변경된 아이템 개수를 확인할 수 있다.

시간이 너무 부족하여 코드 정리를 잘 못했지만 mvc패턴을 잘 적용했다는 것에 높은 점수를 주고 싶다. 그리고 validation 체크를 신경써서 했는데 선생님께서 알아주셔서 뿌듯했다.

컨트롤러(Controller)

[InvtController.java]

package com.multi.gameProject.inventory.controller;

import com.multi.gameProject.common.InvtException;
import com.multi.gameProject.inventory.model.dto.InvtDto;
import com.multi.gameProject.inventory.model.dto.ItemDto;
import com.multi.gameProject.inventory.service.InvtService;

import javax.swing.*;
import java.util.ArrayList;

public class InvtController {

    private InvtService invtService = new InvtService();

    public int getUserCoin(String userId) {

        int coin = 0;
        try {
            coin = invtService.getUserCoin(userId);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"코인 조회 실패, 관리자에 문의하세요 ");
            e.printStackTrace();
        }
        return coin;
    }

    public int getUserScore(String userId) {

        int score = 0;
        try {
            score = invtService.getUserScore(userId);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"점수 조회 실패, 관리자에 문의하세요 ");
            e.printStackTrace();
        }

        return score;
    }

    public int getOutputCoin(String userId, int inputScore) {
        int outputCoin = 0;

        if (inputScore <= getUserScore(userId)) {
            if (inputScore % 100 != 0) {
                JOptionPane.showMessageDialog(null,"100의 배수로 입력해주세요.");

            } else {
                outputCoin = inputScore / 100;
            }
        } else {
            JOptionPane.showMessageDialog(null,"점수가 부족합니다.");
        }

        return outputCoin;
    }

    public int changeScoreToCoin(String userId, int inputScore) {
        int result = 0;

        int finalInput = getOutputCoin(userId, inputScore);

        if (finalInput != 0) {
            try {
                result = invtService.changeScoreToCoin(userId, inputScore);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"변환 실패, 관리자에 문의하세요 ");
                e.printStackTrace();
            }

        }

        return result;
    }

    public int buyItem(InvtDto invtDto) {
        int result = 0;
        try {
            if (invtService.getUserCoin(invtDto.getUserId()) < invtService.getItemPrice(invtDto.getItemNo())) {
                JOptionPane.showMessageDialog(null,"코인이 부족합니다. ");
            } else {
                result = invtService.buyItem(invtDto);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"아이템 구입 실패, 관리자에 문의하세요 ");
            e.printStackTrace();
        }

        return result;
    }

    public ArrayList<ItemDto> getItems() {
        ArrayList<ItemDto> list = null;
        try {
            list = invtService.getItems();
        } catch (InvtException e) {
            JOptionPane.showMessageDialog(null,"아이템 불러오기 실패, 관리자에 문의하세요 ");
            e.printStackTrace();
        }

        return list;
    }

    public int getUserItemCount(InvtDto invtDto) {
        int itemCount = 0;
        try {
            itemCount = invtService.getUserItemCount(invtDto);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"아이템 조회 실패, 관리자에 문의하세요 ");
            e.printStackTrace();
        }

        return itemCount;

    }
}

서비스(Service)

[InvtService.java]

package com.multi.gameProject.inventory.service;

import com.multi.gameProject.common.InvtException;
import com.multi.gameProject.inventory.model.dao.InvtDao;
import com.multi.gameProject.inventory.model.dto.InvtDto;
import com.multi.gameProject.inventory.model.dto.ItemDto;

import java.sql.Connection;
import java.util.ArrayList;

import static com.multi.gameProject.common.JDBCTemplate.*;

public class InvtService {

    private InvtDao invtDao;

    public InvtService() {
        invtDao = new InvtDao();
    }

    public int getUserCoin(String userId) throws InvtException {
        Connection conn = getConnection();
        int coin = invtDao.getUserCoin(conn, userId);

        return coin;
    }

    public int getUserScore(String userId) throws InvtException {
        Connection conn = getConnection();
        int score = invtDao.getUserScore(conn, userId);

        return score;
    }

    public int changeScoreToCoin(String userId, int inputScore) throws InvtException {
        Connection conn = getConnection();
        int result = 0;
        int score = inputScore;
        int coin = inputScore/100;
        int result1 = invtDao.changeScore(conn, userId, score);
        int result2 = invtDao.changeCoin(conn, userId, coin);

        if (result1 > 0 && result2 > 0) {
            commit(conn);
            result = 1;
        } else {
            rollback(conn);
        }

        return result;
    }

    public int getItemPrice(int itemNo) throws InvtException {
        Connection conn = getConnection();

        int price = invtDao.getItemPrice(conn, itemNo);

        return price;
    }

    public ArrayList<ItemDto> getItems() throws InvtException {
        Connection conn = getConnection();

        ArrayList<ItemDto> list = invtDao.getItems(conn);

        return list;
    }

    public int getUserItemCount(InvtDto invtDto) throws InvtException {
        Connection conn = getConnection();
        int count = 0;
        InvtDto userInvt = invtDao.getUserInvt(conn, invtDto);

        if(userInvt != null){
            count = userInvt.getItemCount();
        }

        return count;

    }

    public int buyItem(InvtDto invtDto) throws InvtException {
        Connection conn = getConnection();
        int result = 0;
        int result1;
        int result2;
        String userId = invtDto.getUserId();
        int itemNo = invtDto.getItemNo();
        int price = getItemPrice(itemNo);

        // 기존 인벤토리 존재 여부 확인
        InvtDto userInvt = invtDao.getUserInvt(conn, invtDto);

        if(userInvt == null){
            result1 = invtDao.insertInvt(conn, invtDto);
            result2 = invtDao.changeCoin(conn, userId, -price);
        } else{
            result1 = invtDao.updateInvt(conn, invtDto);
            result2 = invtDao.changeCoin(conn, userId, -price);
        }

        if (result1 > 0 && result2 > 0) {
            commit(conn);
            result = 1;
        } else {
            rollback(conn);
        }

        return result;
    }
}

모델(Model)

DTO

[InvtDto.java]

package com.multi.gameProject.inventory.model.dto;

public class InvtDto {

    private String userId;
    private int itemNo;
    private int itemCount;

    public InvtDto() {
    }

    public InvtDto(String userId, int itemNo) {
        this.userId = userId;
        this.itemNo = itemNo;
    }

    public InvtDto(String userId, int itemNo, int itemCount) {
        this.userId = userId;
        this.itemNo = itemNo;
        this.itemCount = itemCount;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int getItemNo() {
        return itemNo;
    }

    public void setItemNo(int itemNo) {
        this.itemNo = itemNo;
    }

    public int getItemCount() {
        return itemCount;
    }

    public void setItemCount(int itemCount) {
        this.itemCount = itemCount;
    }

    @Override
    public String toString() {
        return "InvtDto{" +
                "userId='" + userId + '\'' +
                ", itemNo=" + itemNo +
                ", itemCount=" + itemCount +
                '}';
    }
}

DAO

[InvtDao.java]

package com.multi.gameProject.inventory.model.dao;

import com.multi.gameProject.common.InvtException;
import com.multi.gameProject.inventory.model.dto.InvtDto;
import com.multi.gameProject.inventory.model.dto.ItemDto;

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import static com.multi.gameProject.common.JDBCTemplate.close;

public class InvtDao {

    private Properties prop = null;

    public InvtDao() {

        try {
            prop = new Properties();
            prop.load(new FileReader("resources/invtquery.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public int getUserCoin(Connection conn, String userId) throws InvtException {
        int coin = 0;

        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = prop.getProperty("getUserCoin");

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, userId);
            rs = ps.executeQuery();

            if (rs.next()) {
                coin = rs.getInt("COIN_COUNT");

            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("getUserCoin 에러 : " + e.getMessage());
        } finally {
            close(rs);
            close(ps);
        }

        return coin;
    }

    public int getUserScore(Connection conn, String userId) throws InvtException {
        int score = 0;

        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = prop.getProperty("getUserScore");

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, userId);
            rs = ps.executeQuery();

            if (rs.next()) {
                score = rs.getInt("TOTAL_SCORE");

            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("getUserScore 에러 : " + e.getMessage());

        } finally {
            close(rs);
            close(ps);
        }
        return score;
    }

    public int changeScore(Connection conn, String userId, int score) throws InvtException {
        int result = 0;

        PreparedStatement ps = null;
        String sql = prop.getProperty("changeScore");

        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, score);
            ps.setString(2, userId);
            result = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("changeScore 에러 : " + e.getMessage());
        } finally {
            close(ps);
        }

        return result;
    }

    public int changeCoin(Connection conn, String userId, int price) throws InvtException {
        int result = 0;

        PreparedStatement ps = null;
        String sql = prop.getProperty("changeCoin");
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, price);
            ps.setString(2, userId);
            result = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("changeCoin 에러 : " + e.getMessage());
        } finally {
            close(ps);
        }

        return result;
    }

    public int getItemPrice(Connection conn, int itemNo) throws InvtException {
        int price = 0;

        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = prop.getProperty("getItemPrice");

        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, itemNo);
            rs = ps.executeQuery();

            if (rs.next()) {
                price = rs.getInt("ITEM_PRICE");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("getItemPrice 에러 : " + e.getMessage());
        } finally {
            close(rs);
            close(ps);
        }

        return price;
    }

    public ArrayList<ItemDto> getItems(Connection conn) throws InvtException {
        ArrayList<ItemDto> list = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = prop.getProperty("getItems");

        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            list = new ArrayList<>();

            while (rs.next()) {
                ItemDto itemDto = new ItemDto();
                itemDto.setItemNo(rs.getInt("ITEM_NO"));
                itemDto.setItemName(rs.getString("ITEM_NAME"));
                itemDto.setItemPrice(rs.getInt("ITEM_PRICE"));

                list.add(itemDto);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("getItems 에러 : " + e.getMessage());
        } finally {
            close(rs);
            close(ps);
        }
        return list;

    }

    public InvtDto getUserInvt(Connection conn, InvtDto invtDto) throws InvtException {

        InvtDto rsDto = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = prop.getProperty("getUserInvt");

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, invtDto.getUserId());
            ps.setInt(2, invtDto.getItemNo());
            rs = ps.executeQuery();

            if (rs.next()) {
                rsDto = new InvtDto();
                rsDto.setUserId(rs.getString("USER_ID"));
                rsDto.setItemNo(rs.getInt("ITEM_NO"));
                rsDto.setItemCount(rs.getInt("ITEM_COUNT"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new InvtException("getUserInvt 에러 : " + e.getMessage());
        } finally {
            close(rs);
            close(ps);
        }

        return rsDto;
    }

    public int insertInvt(Connection conn, InvtDto invtDto) {
        int result = 0;

        PreparedStatement ps = null;
        String sql = prop.getProperty("insertInvt");

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, invtDto.getUserId());
            ps.setInt(2, invtDto.getItemNo());
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps);
        }

        return result;
    }

    public int updateInvt(Connection conn, InvtDto invtDto) {
        int result = 0;

        PreparedStatement ps = null;
        String sql = prop.getProperty("updateInvt");

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, invtDto.getUserId());
            ps.setInt(2, invtDto.getItemNo());
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps);
        }

        return result;
    }
}

뷰(View)

[GeneralUserStorePage.java]

package com.multi.gameProject.inventory.view;

import com.multi.gameProject.generalUsers.model.dto.GeneralUserDto;
import com.multi.gameProject.generalUsers.view.GeneralUserAfterLoginHomePage;
import com.multi.gameProject.generalUsers.view.GeneralUserAfterLoginRankingPage;
import com.multi.gameProject.generalUsers.view.GeneralUserAfterMyBoardPage;
import com.multi.gameProject.generalUsers.view.GeneralUserAfterMyInfoPage;
import com.multi.gameProject.inventory.controller.InvtController;
import com.multi.gameProject.inventory.model.dto.InvtDto;
import com.multi.gameProject.inventory.model.dto.ItemDto;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;


public class GeneralUserStorePage {
    private GeneralUserDto loginDto;
    private String userId;
    private InvtController invtController = new InvtController();
    private JFrame f;
    private Font font2 = new Font("굴림", Font.BOLD, 30);
    private Font font3 = new Font("굴림", Font.BOLD, 20);
    private JPanel headerP;
    private JPanel midP;
    private JPanel footerP;
    private JLabel myCoin2;

    public GeneralUserStorePage(GeneralUserDto loginDto) {
        this.loginDto = loginDto;
        userId = loginDto.getUserId();
    }

    public void storeView() {
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600, 800);
        f.setTitle("코마에 사칙연산 게임");

        initHeaderP();
        initMidP();
        initFooterP();

        f.add(headerP, BorderLayout.PAGE_START);
        f.add(midP, BorderLayout.CENTER);
        f.add(footerP, BorderLayout.PAGE_END);

        f.setVisible(true);
    }

    private void initHeaderP() {
        headerP = new JPanel(new GridLayout(0, 4, 10, 10)); // 위
        headerP.setBackground(new Color(40, 60, 79));
        headerP.setBorder(BorderFactory.createEmptyBorder(30, 10, 40, 10)); // 여백(=padding)

        JButton menuBtn1 = new JButton("내정보");
        JButton menuBtn2 = new JButton("상점");
        JButton menuBtn3 = new JButton("게시판");
        JButton menuBtn4 = new JButton("랭킹");
        menuBtn1.setFont(font2);
        menuBtn2.setFont(font2);
        menuBtn3.setFont(font2);
        menuBtn4.setFont(font2);
        menuBtn1.setBackground(new Color(63, 228, 192));
        menuBtn2.setBackground(new Color(253, 219, 0, 255));
        menuBtn3.setBackground(new Color(63, 228, 192));
        menuBtn4.setBackground(new Color(63, 228, 192));

        headerP.add(menuBtn1);
        headerP.add(menuBtn2);
        headerP.add(menuBtn3);
        headerP.add(menuBtn4);

        menuBtn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new GeneralUserAfterMyInfoPage(loginDto);
                f.dispose();
            }
        });

        menuBtn3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new GeneralUserAfterMyBoardPage(loginDto);
                f.dispose();
            }
        });

        menuBtn4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new GeneralUserAfterLoginRankingPage(loginDto);
                f.dispose();
            }
        });

    }

    private void initMidP() {
        midP = new JPanel(new GridLayout(0, 1, 0, 0)); // 가운데
        midP.setBackground(new Color(40, 60, 79));
        midP.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20)); // 여백(=padding)

        JPanel myCoinP = new JPanel(new GridLayout(0, 2));
        myCoinP.setBackground(Color.CYAN);
        JLabel myCoin1 = new JLabel("나의 코인", 0);
        int coin = invtController.getUserCoin(userId);
        myCoin2 = new JLabel(coin + "개", 0);
        myCoin2.setText(coin+"개");
        myCoin1.setFont(font3);
        myCoin2.setFont(font2);
        myCoinP.add(myCoin1);
        myCoinP.add(myCoin2);
        midP.add(myCoinP);

        ArrayList<ItemDto> list = invtController.getItems();

        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                JPanel itemP = new JPanel(new FlowLayout(0, 30, 0));
                itemP.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
                itemP.setBackground(Color.white);
                ImageIcon itemImg = new ImageIcon("img/" + list.get(i).getImg());
                JLabel itemL = new JLabel("    " + list.get(i).getItemName(), itemImg, 0);
                JLabel itemPrice = new JLabel("코인 " + list.get(i).getItemPrice() + "개", 0);
                itemL.setFont(font3);
                itemPrice.setFont(font3);
                JButton addBtn = new JButton("구매");
                addBtn.setActionCommand(String.valueOf(list.get(i).getItemNo()));
                addBtn.setFont(font2);
                itemP.add(itemL);
                itemP.add(itemPrice);
                itemP.add(addBtn);
                midP.add(itemP);

                addBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int itemNo = Integer.parseInt(e.getActionCommand());
                        InvtDto invtDto = new InvtDto(userId, itemNo, 1);
                        int result = invtController.buyItem(invtDto);

                        if (result > 0) {
                            showDialog("아이템 구매 성공");
                            myCoin2.setText(invtController.getUserCoin(userId) + "개");
                        }
                    }
                });
            }
        }
    }

    private void initFooterP() {
        footerP = new JPanel(new BorderLayout()); // 아래
        footerP.setBackground(new Color(40, 60, 79));
        footerP.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50)); // 여백(=padding)
        JButton goHomeBtn = new JButton("홈으로");
        goHomeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                f.setVisible(false);
                new GeneralUserAfterLoginHomePage(loginDto);
            }
        });
        goHomeBtn.setBorderPainted(false);
        goHomeBtn.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 여백(=padding)
        goHomeBtn.setFont(font2);
        goHomeBtn.setBackground(new Color(63, 228, 192));
        JButton goToInvt = new JButton("내 코인 / 아이템 조회");
        goToInvt.setBorderPainted(false);
        goToInvt.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 여백(=padding)
        goToInvt.setFont(font2);
        goToInvt.setBackground(new Color(63, 228, 192));
        footerP.add(goToInvt, BorderLayout.LINE_START);
        footerP.add(goHomeBtn, BorderLayout.LINE_END);

        goToInvt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CoinInvtPage coinInvt = new CoinInvtPage(loginDto);
                f.setVisible(false);
                coinInvt.coinInvtView();
            }
        });
    }

    public void showDialog(String inform) {
        JOptionPane.showMessageDialog(f, inform);
    }
}

[CoinInvt.java]

package com.multi.gameProject.inventory.view;

import com.multi.gameProject.generalUsers.model.dto.GeneralUserDto;
import com.multi.gameProject.inventory.controller.InvtController;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CoinInvtPage {
    private GeneralUserDto loginDto;
    private String userId;
    private InvtController invtController = new InvtController();
    private JFrame f;
    private Font font2 = new Font("굴림", Font.BOLD, 30);
    private Font font3 = new Font("굴림", java.awt.Font.BOLD, 20);
    private JPanel headerP;
    private JPanel midP;
    private JPanel footerP;
    private JTextField input;
    private JTextField output;
    private int coin;
    private int score;
    private JLabel myCoin2;
    private JLabel myScore2;
    private JButton menuBtn1;
    private JButton menuBtn2;

    public CoinInvtPage(GeneralUserDto loginDto) {
        this.loginDto = loginDto;
        userId = loginDto.getUserId();
    }

    public void coinInvtView() {
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600, 800);
        f.setTitle("코마에 사칙연산 게임");

        initHeaderP();
        initMidP();
        initFooterP();

        f.add(headerP, BorderLayout.PAGE_START);
        f.add(midP, BorderLayout.CENTER);
        f.add(footerP, BorderLayout.PAGE_END);

        f.setVisible(true);
    }

    private void initHeaderP() {
        headerP = new JPanel(new GridLayout(0, 2, 50, 50)); // 위
        headerP.setBackground(new Color(40, 60, 79));
        headerP.setBorder(BorderFactory.createEmptyBorder(30, 100, 40, 100)); // 여백(=padding)

        menuBtn1 = new JButton("코인");
        menuBtn2 = new JButton("아이템");

        menuBtn1.setFont(font2);
        menuBtn2.setFont(font2);

        menuBtn1.setBackground(new Color(253, 219, 0, 255));
        menuBtn2.setBackground(new Color(63, 228, 192));

        headerP.add(menuBtn1);
        headerP.add(menuBtn2);


        menuBtn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                f.dispose();
                new ItemInvtPage(loginDto).ItemInvtView();
            }
        });
    }

    private void initMidP() {
        midP = new JPanel(new GridLayout(0, 1)); // 가운데
        midP.setBackground(new Color(40, 60, 79));
        midP.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20)); // 여백(=padding)

        JPanel myCoinP = new JPanel(new GridLayout(0, 2));
        JPanel myScoreP = new JPanel(new GridLayout(0, 2));
        JPanel changeP = new JPanel(new GridLayout(0, 3, 10, 0));

        JLabel myCoin1 = new JLabel("나의 코인", 0);
        myCoin2 = new JLabel("개", 0);
        coin = invtController.getUserCoin(userId);
        myCoin2.setText(coin+"개");
        myCoin1.setFont(font3);
        myCoin2.setFont(font2);
        myCoinP.add(myCoin1);
        myCoinP.add(myCoin2);

        JLabel myScore1 = new JLabel("보유 점수", 0);
        score = invtController.getUserScore(userId);
        myScore2 = new JLabel(score + "점", 0);
        myScore1.setFont(font3);
        myScore2.setFont(font2);
        myScoreP.add(myScore1);
        myScoreP.add(myScore2);

        JLabel changeTitle1 = new JLabel("점수 ▶ 코인 전환하기" + "   (※ 점수 100점당 코인 1개)", 0);
        changeTitle1.setFont(font3);
        changeTitle1.setForeground(Color.white);

        JPanel changeScoreP = new JPanel(new GridLayout(0, 1));
        JLabel changeScoreL = new JLabel("전환할 점수 (점)", 0);
        input = new JTextField("", 10);
        input.setHorizontalAlignment(0);

        JPanel arrorwP = new JPanel(null);
        ImageIcon arrowImg = new ImageIcon("img/arrow.png");
        JLabel arrowL = new JLabel(arrowImg, 0);
        arrowL.setBounds(50, 10, 80, 80);
        JButton checkBtn = new JButton("확인하기");
        checkBtn.setFont(new Font("굴림", Font.BOLD, 15));
        checkBtn.setBackground(Color.yellow);
        checkBtn.setBounds(38, 85, 100, 25);

        arrorwP.add(arrowL);
        arrorwP.add(checkBtn, BorderLayout.SOUTH);

        JPanel changeCoinP = new JPanel(new GridLayout(0, 1));
        JLabel changeCoinL = new JLabel("전환될 코인 (개)", 0);
        output = new JTextField(10);
        output.setEditable(false);
        output.setBackground(Color.white);
        output.setHorizontalAlignment(0);

        checkBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int inputScore;
                if (input.getText().length() == 0 || input.getText().equals("0")) {
                    showDialog("전환할 점수를 입력해주세요.");
                } else {
                    inputScore = Integer.parseInt(input.getText());

                    int outputCoin = invtController.getOutputCoin(userId, inputScore);
                    output.setText(outputCoin + "개");
                }
            }
        });

        changeScoreL.setFont(font3);
        input.setFont(font2);

        changeCoinL.setFont(font3);
        output.setFont(font2);

        changeScoreP.add(changeScoreL);
        changeScoreP.add(input);
        changeCoinP.add(changeCoinL);
        changeCoinP.add(output);

        changeP.add(changeScoreP);
        changeP.add(arrorwP);
        changeP.add(changeCoinP);

        midP.add(myCoinP);
        midP.add(myScoreP);
        midP.add(changeTitle1);
        midP.add(changeP);

    }


    private void initFooterP() {
        footerP = new JPanel(new BorderLayout()); // 아래
        footerP.setBackground(new Color(40, 60, 79));
        footerP.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50)); // 여백(=padding)
        JButton GoToStoreBtn = new JButton("상점으로");
        GoToStoreBtn.setBorderPainted(false);
        GoToStoreBtn.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 여백(=padding)
        GoToStoreBtn.setFont(font2);
        GoToStoreBtn.setBackground(new Color(63, 228, 192));
        JButton changeBtn = new JButton(" 전  환 ");
        changeBtn.setBorderPainted(false);
        changeBtn.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 여백(=padding)
        changeBtn.setFont(font2);
        changeBtn.setBackground(new Color(63, 228, 192));
        footerP.add(changeBtn, BorderLayout.LINE_START);
        footerP.add(GoToStoreBtn, BorderLayout.LINE_END);

        changeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (input.getText().length() == 0 || input.getText() == "0") {
                    showDialog("전환할 점수를 입력해주세요.");
                } else {
                    int inputScore = Integer.parseInt(input.getText());

                    int result = invtController.changeScoreToCoin(userId, inputScore);

                    if (result == 1) {
                        input.setText("");
                        output.setText("");
                        myCoin2.setText(invtController.getUserCoin(userId) + "개");
                        myScore2.setText(invtController.getUserScore(userId) + "개");
                        showDialog("전환완료");
                    } else {
                        input.setText("");
                        output.setText("");
                        showDialog("전환실패");
                    }
                }

            }
        });

        GoToStoreBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new GeneralUserStorePage(loginDto).storeView();
                f.dispose();
            }
        });
    }

    public void showDialog(String inform) {
        JOptionPane.showMessageDialog(f, inform);
    }
}

[ItemInvt.java]

package com.multi.gameProject.inventory.view;

import com.multi.gameProject.generalUsers.model.dto.GeneralUserDto;
import com.multi.gameProject.inventory.controller.InvtController;
import com.multi.gameProject.inventory.model.dto.InvtDto;
import com.multi.gameProject.inventory.model.dto.ItemDto;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class ItemInvtPage {
    private GeneralUserDto loginDto;
    private String userId;
    private InvtController invtController = new InvtController();
    private JFrame f;
    private Font font2 = new Font("굴림", Font.BOLD, 30);
    private Font font3 = new Font("굴림", Font.BOLD, 20);
    private JPanel headerP;
    private JPanel midP;
    private JPanel footerP;

    public ItemInvtPage(GeneralUserDto loginDto) {
        this.loginDto = loginDto;
        userId = loginDto.getUserId();
    }

    public void ItemInvtView() {
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600, 800);
        f.setTitle("코마에 사칙연산 게임");

        initHeaderP();
        initMidP();
        initFooterP();

        f.add(headerP, BorderLayout.PAGE_START);
        f.add(midP, BorderLayout.CENTER);
        f.add(footerP, BorderLayout.PAGE_END);

        f.setVisible(true);
    }

    private void initHeaderP() {
        headerP = new JPanel(new GridLayout(0, 2, 50, 50)); // 위
        headerP.setBackground(new Color(40, 60, 79));
        headerP.setBorder(BorderFactory.createEmptyBorder(30, 100, 40, 100)); // 여백(=padding)

        JButton menuBtn1 = new JButton("코인");
        JButton menuBtn2 = new JButton("아이템");

        menuBtn1.setFont(font2);
        menuBtn2.setFont(font2);

        menuBtn1.setBackground(new Color(63, 228, 192));
        menuBtn2.setBackground(new Color(253, 219, 0, 255));
        menuBtn2.setForeground(Color.black);

        headerP.add(menuBtn1);
        headerP.add(menuBtn2);

        menuBtn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                f.dispose();
                new CoinInvtPage(loginDto).coinInvtView();
            }
        });
    }

    private void initMidP() {
        midP = new JPanel(new GridLayout(0, 1)); // 가운데
        midP.setBackground(new Color(40, 60, 79));
        midP.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20)); // 여백(=padding)

        JLabel titleL = new JLabel("나의 아이템");
        titleL.setFont(font2);
        titleL.setOpaque(true);
        titleL.setBackground(Color.cyan);
        titleL.setForeground(new Color(40, 60, 79));
        titleL.setHorizontalAlignment(0);
        midP.add(titleL);

        ArrayList<ItemDto> list = invtController.getItems();

        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                InvtDto invtDto = new InvtDto(userId, list.get(i).getItemNo());
                JPanel itemP = new JPanel(new FlowLayout(0, 50, 0));
                itemP.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
                itemP.setBackground(Color.white);
                ImageIcon itemImg = new ImageIcon("img/" + list.get(i).getImg());
                JLabel itemL = new JLabel("    " + list.get(i).getItemName(), itemImg, 0);
                JLabel count = new JLabel("      " + invtController.getUserItemCount(invtDto) + "개", 0);
                itemL.setFont(font3);
                count.setFont(font2);
                itemP.add(itemL);
                itemP.add(count);
                midP.add(itemP);
            }
        }
    }

    private void initFooterP() {
        footerP = new JPanel(new BorderLayout()); // 아래
        footerP.setBackground(new Color(40, 60, 79));
        footerP.setBorder(BorderFactory.createEmptyBorder(50, 0, 50, 50)); // 여백(=padding)
        JButton GoToStoreBtn = new JButton("상점으로");
        GoToStoreBtn.setBorderPainted(false);
        GoToStoreBtn.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 여백(=padding)
        GoToStoreBtn.setFont(font2);
        GoToStoreBtn.setBackground(new Color(63, 228, 192));
        footerP.add(GoToStoreBtn, BorderLayout.LINE_END);

        GoToStoreBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                f.setVisible(false);
                GeneralUserStorePage store = new GeneralUserStorePage(loginDto);
                store.storeView();
            }
        });

    }

    public void showDialog(String inform) {
        JOptionPane.showMessageDialog(f, inform);
    }

}

단위테스트

마지막으로 단위테스트를 했다.
내가 기획하고 설계했던대로 잘 나온 것 같다. 약간 아쉬움은 남지만 그래도 만족스러운 결과를 얻어 매우 기쁘다.
다음에는 지난번 자습으로 만들었던 to-do-list를 JDBC로 DB와 연결하여 완성해볼 계획이다.

본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.

profile
성장하는 개발자, 하지은입니다.

0개의 댓글