Skip to content

Latest commit

 

History

History
95 lines (79 loc) · 3.03 KB

220102.md

File metadata and controls

95 lines (79 loc) · 3.03 KB

Day 86

파이썬으로 배우는 게임 개발 실전편

Chapter 4

맵 에디터 제작하기 1

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class WindowClass(QWidget):
    def __init__(self):
        super().__init__()

        self.chip = 0
        self.map_data = []
        for i in range(9):
            self.map_data.append([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

        self.img = [
            QImage('Python_workspace\python_game\image\dot_eat\chip00.png'),
            QImage('Python_workspace\python_game\image\dot_eat\chip01.png'),
            QImage('Python_workspace\python_game\image\dot_eat\chip02.png'),
            QImage('Python_workspace\python_game\image\dot_eat\chip03.png')
        ]
        self.setMouseTracking = True

        self.initUI()
        self.draw_map()
        self.draw_chip()

    def initUI(self):
        self.setFixedSize(820, 560)
        self.n = QLabel(self)
        self.n.move(10, 10)
        self.n.resize(720, 540)
        self.o = QLabel(self)
        self.o.move(740, 10)
        self.o.resize(60, 540)
        self.setWindowTitle('Map editor')

    def mousePressEvent(self, e):
        self.mx = int(e.x() / 60)
        self.my = int(e.y() / 60)
        if e.x() >= 740:
            self.select_chip()
        else:
            self.set_map()

    def draw_map(self):
        pixmap = QPixmap(self.n.size())
        qp = QPainter(pixmap)
        for y in range(9):
            for x in range(12):
                qp.drawImage(QRect(60 * x, 60 * y, 60, 60), self.img[self.map_data[y][x]])
        qp.end()
        self.n.setPixmap(pixmap)

    def draw_chip(self):
        pixmap = QPixmap(self.o.size())
        qp = QPainter(pixmap)
        for i in range(len(self.img)):
            qp.drawImage(QRect(0, i * 60, 60, 60), self.img[i])
        qp.setPen(QPen(Qt.red, 3))
        qp.drawRect(1, 1 + 60 * self.chip, 57, 57)
        qp.end()
        self.o.setPixmap(pixmap)

    def set_map(self):
        if 0 <= self.mx and self.mx <= 11 and 0 <= self.my and self.my <= 8:
            self.map_data[self.my][self.mx] = self.chip
            self.draw_map()

    def select_chip(self):
        if 0 <= self.my and self.my < len(self.img):
            self.chip = self.my
            self.draw_chip()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_W = WindowClass()
    main_W.show()
    sys.exit(app.exec_())

이번에는 기존에 paintEvent에 모두 몰아 넣어서 복잡했던 것을 개선하기 위한 방법 중 하나를 찾았다.

paintEvent가 아닌 함수에서 QPainter를 이용한 방법이다.

함수 내에서 QPixmap에 그리고 라벨에 setPixmap으로 이미지를 넣는 방식이다.

이 방식을 사용하면 GUI 구성 자체가 좀 다양해질 것이다.

찾은 곳

이 방식이 게임과 같이 동시처리가 중요한 부분에서도 사용 가능할 것인지 확인해봐야 할 것 같다.