포토샵

from tkinter import *
from tkinter .filedialog import *
from tkinter .simpledialog import *
from PIL import Image, ImageFilter, ImageEnhance, ImageOps

# 함수 선언 부분
def displayImage(img, width, height):
    global window, canvas, paper, photo, photo2, oriX, oriY
    
    window.geometry(str(width) + "x" + str(height))
    if canvas != None:
        canvas.destroy()
    
    canvas = Canvas(window, width=width, height=height)
    paper = PhotoImage(width=width, height=height)
    canvas.create_image((width / 2, height / 2), image=paper, state="normal")
    rgbString = ""
    rgbImage = img.convert('RGB')
    for i in range(0, height):
        tmpString = ""
        for k in range(0, width):
            r, g, b = rgbImage.getpixel((k, i))
            tmpString += "#%02x%02x%02x " % (r, g, b) #x 뒤에 한 칸 공백
        rgbString += "{" + tmpString + "} " # } 뒤에 한 칸 공백
    paper.put(rgbString)
    canvas.pack()

def func_open():
    global window, canvas, paper, photo, photo2, oriX, oriY
    readFp = askopenfilename(parent=window, filetypes=(("모든 그림 파일", "*.jpg;*.jpeg;*.bmp;*.png;*.tif;*.gif"),("모든 파일", "*.*")))
    photo = Image.open(readFp).convert('RGB')
    oriX = photo.width
    oriY = photo.height

    photo2 = photo.copy()
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_save():
    global window, canvas, paper, photo, photo2, oriX, oriY

    if photo2 == None:
        return
    saveFp = asksaveasfile(parent = window, mode = "w", defaultextension= ".jpg",
                filetypes = (("JPG 파일", "*.jpg; *.jpeg"), ("모든 파일", "*.*")))
    
    photo2.save(saveFp.name)

def func_exit():
    exit()

def func_zoomin():
    global window, canvas, paper, photo, photo2, oriX, oriY
    scale = askinteger("확대", "확대할 배율을 입력하세요", minvalue= 2, maxvalue= 4)
    photo2 = photo.copy()
    photo2 = photo2.resize((int(oriX*scale), int(oriY*scale)))
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_zoomout():
    global window, canvas, paper, photo, photo2, oriX, oriY
    scale = askinteger("축소", "축소할 배율을 입력하세요", minvalue= 2, maxvalue= 4)
    photo2 = photo.copy()
    photo2 = photo2.resize((int(oriX/scale), int(oriY/scale)))
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_mirror1():
    global window, canvas, paper, photo, photo2, oriX, oriY
    photo2 = photo.copy()
    photo2 = photo2.transpose(Image.FLIP_TOP_BOTTOM)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_mirror2():
    global window, canvas, paper, photo, photo2, oriX, oriY
    photo2 = photo.copy()
    photo2 = photo2.transpose(Image.FLIP_LEFT_RIGHT)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_rotate():
    global window, canvas, paper, photo, photo2, oriX, oriY
    dgree = askinteger("회전", "회전할 각도를 입력하세요", minvalue= 0, maxvalue= 360)
    photo2 = photo.copy()
    photo2 = photo2.rotate(dgree, expand=True)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_bright():
    global window, canvas, paper, photo, photo2, oriX, oriY
    value = askfloat("밝게", "값을 입력하세요(1.0 ~ 10.0)", minvalue= 1.0, maxvalue= 10.0)
    photo2 = photo.copy()
    photo2 = ImageEnhance.Brightness(photo2).enhance(value)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_dark():
    global window, canvas, paper, photo, photo2, oriX, oriY
    value = askfloat("어둡게", "값을 입력하세요(0.0 ~ 1.0)", minvalue= 0.0, maxvalue= 1.0)
    photo2 = photo.copy()
    photo2 = ImageEnhance.Brightness(photo2).enhance(value)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_blur():
    global window, canvas, paper, photo, photo2, oriX, oriY
    photo2 = photo.copy()
    photo2 = photo2.filter(ImageFilter.BLUR)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_emboss():
    global window, canvas, paper, photo, photo2, oriX, oriY
    photo2 = photo.copy()
    photo2 = photo2.filter(ImageFilter.EMBOSS)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

def func_bw():
    global window, canvas, paper, photo, photo2, oriX, oriY
    photo2 = photo.copy()
    photo2 = ImageOps.grayscale(photo2)
    newX = photo2.width
    newY = photo2.height
    displayImage(photo2, newX, newY)

# 전역 변수 선언 부분
window, canvas, paper = None, None, None
photo, photo2 = None, None
oriX, oriY = 0, 0

# 메인 코드 부분
window = Tk()
window.geometry("250x250")
window.title("미니 포토샵")

mainMenu = Menu(window)
window.config(menu=mainMenu)

fileMenu = Menu(mainMenu)
mainMenu.add_cascade(label="파일", menu=fileMenu)
fileMenu.add_command(label="파일 열기", command=func_open)
fileMenu.add_command(label="파일 저장", command=func_save)
fileMenu.add_separator()
fileMenu.add_command(label="프로그램 종료", command=func_exit)

imageMenu1 = Menu(mainMenu)
mainMenu.add_cascade(label="이미지 처리(1)", menu=imageMenu1)
imageMenu1.add_command(label="확대", command=func_zoomin)
imageMenu1.add_command(label="축소", command=func_zoomout)
imageMenu1.add_separator()
imageMenu1.add_command(label="상하 반전", command=func_mirror1)
imageMenu1.add_command(label="좌우 반전", command=func_mirror2)
imageMenu1.add_command(label="회전", command=func_rotate)

imageMenu2 = Menu(mainMenu)
mainMenu.add_cascade(label="이미지 처리(2)", menu=imageMenu2)
imageMenu2.add_command(label="밝게", command=func_bright)
imageMenu2.add_command(label="어둡게", command=func_dark)
imageMenu2.add_separator()
imageMenu2.add_command(label="블러링", command=func_blur)
imageMenu2.add_command(label="엠보싱", command=func_emboss)
imageMenu2.add_separator()
imageMenu2.add_command(label="흑백 이미지", command=func_bw)

window.mainloop()

 

 

게임

import pygame
import random
import sys


## 함수 선언 부분 ##
def paintEntity(entity, x, y):
    monitor.blit(entity, (int(x), int(y)))


def writeScore(score):
    myFont = pygame.font.Font('ch14/NanumGothic.ttf', 20)  # 한글 폰트
    txt = myFont.render(u'파괴한 우주괴물 수 : ' + str(score), True, (255-r, 255-g, 255-b))
    monitor.blit(txt, (10, sheight - 40))


def playGame():
    global monitor, ship, monster, missile

    r = random.randrange(0, 256)
    g = random.randrange(0, 256)
    b = random.randrange(0, 256)

    # 우주선의 초기 위치와 키보드를 눌렀을 때 이동량을 저장할 변수를 선언
    shipX = swidth / 2
    shipY = sheight * 0.8
    dx, dy = 0, 0

    # 우주괴물을 무작위로 추출하고 크기와 위치를 설정
    monster = pygame.image.load(random.choice(monsterImage))
    monsterSize = monster.get_rect().size
    monsterX = 0
    monsterY = random.randrange(0, int(swidth * 0.3))
    monsterSpeed = random.randrange(1, 5)

    # 미사일 좌표 초기화
    missileX, missileY = None, None

    # 맞춘 우주괴물 숫자를 저장할 변수
    fireCount = 0

    # 무한 반복
    while True:
        (pygame.time.Clock()).tick(50)
        monitor.fill((r, g, b))  # 게임 진행을 늦춘다(10~100 정도가 적당)

        # 키보드나 마우스 이벤트가 들어오는지 체크
        for e in pygame.event.get():
            if e.type in [pygame.QUIT]:
                pygame.quit()
                sys.exit()

            if e.type in [pygame.KEYDOWN]:
                if e.key == pygame.K_LEFT:
                    dx = -5
                elif e.key == pygame.K_RIGHT:
                    dx = +5
                elif e.key == pygame.K_UP:
                    dy = -5
                elif e.key == pygame.K_DOWN:
                    dy = +5
                elif e.key == pygame.K_SPACE:
                    if missileX == None:  # 미사일을 쏜 적이 없다면
                        missileX = shipX + shipSize[0] / 2
                        missileY = shipY  # 우주선 위치에서 미사일을 발사

            if e.type in [pygame.KEYUP]:
                if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT or \
                   e.key == pygame.K_UP or e.key == pygame.K_DOWN:
                    dx, dy = 0, 0

        # 우주선이 화면 안에서만 움직이게 한다.
        if (0 < shipX + dx and shipX + dx <= swidth - shipSize[0]) and \
           (sheight / 2 < shipY + dy and shipY + dy <= sheight - shipSize[1]):
            shipX += dx
            shipY += dy

        paintEntity(ship, shipX, shipY)

        # 우주괴물이 자동으로 나타나 왼쪽에서 오른쪽으로 움직인다.
        monsterX += monsterSpeed
        if monsterX > swidth:
            monsterX = 0
            monsterY = random.randrange(0, int(swidth * 0.3))
            monster = pygame.image.load(random.choice(monsterImage))
            monsterSize = monster.get_rect().size
            monsterSpeed = random.randrange(1, 5)

        paintEntity(monster, monsterX, monsterY)

        # 미사일을 화면에 표시한다.
        if missileX != None:
            missileY -= 10
            if missileY < 0:
                missileX, missileY = None, None

        # 우주괴물이 미사일에 맞았는지 체크
        if missileX != None:
            paintEntity(missile, missileX, missileY)
            if (monsterX < missileX and missileX < monsterX + monsterSize[0]) and \
               (monsterY < missileY and missileY < monsterY + monsterSize[1]):
                fireCount += 1  # 우주괴물을 맞혔을 때
                
                monster = pygame.image.load(random.choice(monsterImage))
                monsterSize = monster.get_rect().size
                monsterX = 0
                monsterY = random.randrange(0, int(swidth * 0.3))
                monsterSpeed = random.randrange(1, 5)
                missileX, missileY = None, None

        writeScore(fireCount)  # 점수를 화면에 출력
        pygame.display.update()  # 화면을 업데이트


## 전역 변수 선언 부분 ##
r, g, b = [0] * 3
swidth, sheight = 500, 700
monitor = None
ship, shipSize = None, 0
monsterImage = ['ch14/game_image/monster01.png', 'ch14/game_image/monster02.png', 'ch14/game_image/monster03.png', 'ch14/game_image/monster04.png', 
                'ch14/game_image/monster05.png', 'ch14/game_image/monster06.png', 'ch14/game_image/monster07.png', 'ch14/game_image/monster08.png', 
                'ch14/game_image/monster09.png', 'ch14/game_image/monster10.png']
monster = None
missile = None

## 메인 코드 부분 ##
pygame.init()
monitor = pygame.display.set_mode((swidth, sheight))
pygame.display.set_caption('우주괴물 무찌르기')

ship = pygame.image.load('ch14/game_image/ship01.png')
shipSize = ship.get_rect().size
missile = pygame.image.load('ch14/game_image/missile.png')

playGame()

 

*폰트는 여기서 다운 받으면 된다.

https://hangeul.naver.com/font

'Language > Python' 카테고리의 다른 글

데이터베이스  (1) 2024.12.05
객체지향 프로그래밍  (1) 2024.12.05
파일 입출력  (0) 2024.12.05
윈도 프로그래밍  (2) 2024.12.05
함수와 모듈  (0) 2024.12.05

+ Recent posts