Coding/JavsScript 삽질기2025. 3. 18. 01:07

오래전에 친구의 PDA로 열심히 하였던 Crazy Daisy Game의 클론을 만들어 보았다.

플레이하기: http://chobocho.com/game/daisy/index.html

 

CrazyDaisy Game

Version V0.2

chobocho.com

 

 

어떻게 만들었는가?

1. 게임은 아래와 같이 서로 인접한 잎이 같은 색인 경우 없어 지는 것이 기본 룰이다.

그래서 먼저 아래와 같이 서로 인접한 잎을 숫자로 표시하였다.

 

2. 그리고 실제 매번 체크해야 하는 인접 꽃잎의 정보는 아래와 같이 테이블을 만들었다.

[ 꽃번호 * 10 + 꽃잎번호, 인접 꽃번호 * 10 + 꽃잎번호]의 쌍으로 만들었고,

가운데 있는 꽃을 0번으로, 3시 방향의 꽃을 1로 시계 방향으로 돌아가면서 번호가 증가 한다고 가정 하였다.

그리고 아래 코드를 이용하여 현재 상태에서 마주 하는 꽃잎이 있는 지를 체크 하였다.

자세한 내용은 아래 전체 소스 코드를 참고 하면 됩니다. ^^

전체 소스코드: https://github.com/chobocho/daisygame

 

GitHub - chobocho/daisygame: Daisy Game

Daisy Game . Contribute to chobocho/daisygame development by creating an account on GitHub.

github.com

 

Posted by chobocho
Coding/Python 삽질기2025. 2. 27. 19:31

JetBrain AI Assistant를 이용하여 근무시간표를 짜주는 스크립트를 만들어 보았다.

1차 도전 ChatGPT 4o로 모델을 설정하고 아래와 같이 요청했다.

아래 조건에 해당하는 엑셀 파일을 생성하는 파이썬 스크립트를 만들어 주세요.
1. xx년 yy월을 입력 받아서 해당 연월의 달력을 만들어주세요
2. 일요일은 빨간색 글자로 표시해 주세요.
3. 토요일은 파란색 글자로 표시해 주세요.
4. 휴일은 빨간색 글자로 표시해 주세요.
5. 휴일을 설정할 수 있는 holiday 필드를 만들어 주세요
6. 근무자 리스트를 입력 할 수 있는 worker 리스트 변수를 만들어 주세요
7. 근무자 리스트에는 아래와 같은 형식의 딕셔너리 자료구조를 이용해서 근무자의 제한 조건을 받게 해주세요
   {최대 근무일수: N, 휴일근무가능: Yes or No, 일요일 근무 가능: Yes or No, 토요일 근무 가능: Yes or No, 근무 불가 날짜 리스트:[]}
8. 각 날짜 아래에는 근무자 이름이 표시되게 해주세요.

작성된 코드를 실행하니 뭐가 하나씩 부족했다.

몇번을 버그리포팅을 하다가, ChatGPT o1으로 모델을 변경하고, 다시 작성을 요청했다.

import calendar
from itertools import cycle
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment


def create_calendar(year, month, holidays, workers):
    # '일요일'을 주의 시작으로 설정
    calendar.setfirstweekday(calendar.SUNDAY)
    # monthdayscalendar: 한 달을 주 단위로 나눈 2차원 리스트 반환
    # 예: [[0, 0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11, 12], ...]
    #    -> [일, 월, 화, 수, 목, 금, 토]
    month_matrix = calendar.monthcalendar(year, month)

    # 워크북 및 워크시트 생성
    wb = Workbook()
    ws = wb.active
    ws.title = f"{year}년 {month}월"

    # 헤더 (일~토)
    headers = ["일", "월", "화", "수", "목", "금", "토"]
    for col, header in enumerate(headers, start=1):
        cell = ws.cell(row=1, column=col)
        cell.value = header
        cell.font = Font(bold=True)
        cell.alignment = Alignment(horizontal="center")

    # 색상 스타일
    red_font = Font(color="FF0000")  # 빨간색 → 일요일 / 공휴일
    blue_font = Font(color="0000FF")  # 파란색 → 토요일

    # 근무자 순환 (cycle)
    worker_cycle = cycle(workers)

    # 달력에 날짜 및 근무자 표시
    # month_matrix는 각 주(week)에 대해 일~토(7개) 날짜를 리스트로 갖고 있음
    # 일자(day_num)가 0이면 그 주에 해당 요일은 비어있음을 의미
    # 주마다 2줄(첫 줄: 날짜, 둘째: 근무자)
    start_row = 2
    for week_index, week in enumerate(month_matrix):
        # 한 주의 날짜들을 표시할 행(week_row) 계산
        # 첫 번째 주 -> start_row=2, 두 번째 주 -> 4, 세 번째 주 -> 6, ...
        week_row = start_row + (week_index * 2)

        for col_index, day_num in enumerate(week, start=1):
            if day_num == 0:
                # 0이면 해당 칸이 비어있는 날이므로 건너뜀
                continue

            # 날짜 표시 (week_row 행, col_index 열)
            day_cell = ws.cell(row=week_row, column=col_index)
            day_cell.value = day_num
            day_cell.alignment = Alignment(horizontal="center")

            # 요일별 색상 설정
            if col_index == 1:  # 일요일 (컬럼 1)
                day_cell.font = red_font
            elif col_index == 7:  # 토요일 (컬럼 7)
                day_cell.font = blue_font
            # 공휴일(holidays)에 해당한다면 빨간색 추가 적용
            if day_num in holidays:
                day_cell.font = red_font

            # 근무자 표시 (날짜 아래 한 줄)
            worker_cell = ws.cell(row=week_row + 1, column=col_index)
            worker = next(worker_cycle, None)
            worker_cell.value = worker["이름"] if worker else ""
            worker_cell.alignment = Alignment(horizontal="center")

    # 엑셀 파일 저장
    file_name = f"{year}_{month}_calendar.xlsx"
    wb.save(file_name)
    print(f"{file_name} 파일이 생성되었습니다!\n")


# 테스트용 코드
if __name__ == "__main__":
    year = 2023
    month = 11
    holidays = [5, 15, 25]
    workers = [
        {"이름": "홍길동", "최대 근무일수": 5, "휴일근무가능": "Yes", "일요일 근무 가능": "No", "토요일 근무 가능": "Yes", "근무 불가 날짜 리스트": [5]},
        {"이름": "김철수", "최대 근무일수": 7, "휴일근무가능": "No", "일요일 근무 가능": "Yes", "토요일 근무 가능": "No", "근무 불가 날짜 리스트": [12]},
        {"이름": "박영희", "최대 근무일수": 6, "휴일근무가능": "Yes", "일요일 근무 가능": "Yes", "토요일 근무 가능": "Yes", "근무 불가 날짜 리스트": [20]},
    ]

    create_calendar(year, month, holidays, workers)

몇 번의 추가 질문 끝에 위와 같은 스크립트를 얻을 수 있었다.

실행 결과

결론적으로, AI를 잘 쓰기 위해서는 개인의 수련이 필요한 것 같다.

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Jupyter notebook 팁  (0) 2024.05.11
[SQL] BEGIN TRANSACTION  (0) 2024.03.07
Cardioid 그리기  (0) 2024.02.17
Posted by chobocho
Coding/Java 삽질기2024. 6. 25. 01:02
 // 한번에 원하는 위치로 이동하기
 ebookListView.setSelection(loadCurrentPosition())
// 현재 보이는 첫 번째 줄 위치 가져오기
ebookListView.firstVisiblePosition

 

Posted by chobocho
Coding/Tip2024. 5. 11. 09:56

구글과 바이두에서 100 + 20% 를 계산하면 아래와 같이 차이가 발생한다.
이는 한국은 미국식을 따르고 중국은 중국식 계산을 따르기 때문이라고 한다.

이렇게 우리가 생각하지 못한 작은 부분에서도 나라별로 차이가 발생한다.



Posted by chobocho
Coding/Python 삽질기2024. 5. 11. 00:34

1. Tab : 자동 완성

2. Shift + Tab : 함수의 설명을 보여준다 (Docstring)

3. ESC (명령어 모드) 에서 Shfit + L : 줄번호를 보여준다

 

4. ESC (명령어 모드) 에서 D, D : 해당 셀을 삭제 한다

5. ESC (명령어 모드) 에서 A : 해당 셀 아래에 새로운 행을 추가한다

6. Ctrl + Enter : 해당 셀을 실행한다

7. Alt + Enter :  해당 셀을 실행하고 아래에 새로운 셀을 추가한다

8. Shift + Enter : 해당 셀을 실행하고 아래 셀로 이동한다. 만약 아래 셀이 없으면 새로운 셀을 추가한다.

'Coding > Python 삽질기' 카테고리의 다른 글

AI로 근무 시간 짜주는 스크립트 만들어 보기  (0) 2025.02.27
[SQL] BEGIN TRANSACTION  (0) 2024.03.07
Cardioid 그리기  (0) 2024.02.17
Posted by chobocho
Coding/Java 삽질기2024. 3. 8. 00:36

IntelliJ에 있는 유용한 기능 중 하나가 JShell 콘솔이다.

아래와 같이 입력 후, 실행을 하면

결과를 실행 창에서 볼 수 있다.

 

Posted by chobocho
Coding/Python 삽질기2024. 3. 7. 00:45

Python으로 작성한 SQL문에서 대량의 insert를 수행시 느려지는 문제가 있어서, 

DB전문가에게 문의를 하니, 간단히 답을 알려 주셨다.

해결책은 "BEGIN TRANSACTION"을 사용하면 되는 것이었다.

이 한줄을 넣고 나니, 10배 이상 속도가 빨라졌다;;

[기존코드]

    def insert(self, data):
        insert_memo_sql = '''INSERT INTO minim(title, memo) VALUES(?, ?);'''
        try:
            cur = self.db_conn.cursor()
            cur.execute(insert_memo_sql, (data[0], data[1]))
            self.db_conn.commit()
            print(cur.lastrowid)
            return cur.lastrowid
        except sqlite3.Error as e:
            print(e)
        return -1

[개선코드]

    def insert_bigdata(self, big_data):
        insert_memo_sql = '''INSERT INTO minim(title, memo) VALUES(?, ?);'''
        try:
            cur = self.db_conn.cursor()
            cur.execute("BEGIN TRANSACTION")
            for data in big_data:
                cur.execute(insert_memo_sql, (data[0], data[1]))
            self.db_conn.commit()
            print(cur.lastrowid)
            return cur.lastrowid
        except sqlite3.Error as e:
            print(e)
            self.db_conn.rollback()  # rollback the transaction if there's any error
        return -1

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Jupyter notebook 팁  (0) 2024.05.11
Cardioid 그리기  (0) 2024.02.17
[Python] PNG to ICO 변환 하기  (0) 2024.01.04
Posted by chobocho
Coding/Python 삽질기2024. 2. 17. 19:16
import math
import pygame


def init_game():
    pygame.init()
    pygame.key.set_repeat(0)
    canvas = pygame.display.set_mode((800, 600))
    fps_clock = pygame.time.Clock()
    return canvas, fps_clock


def main():
    canvas, fps_clock = init_game()

    title = 'Cardioid'
    pygame.display.set_caption(title)
    max_dots = 300

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return

        draw_cardioid(canvas, max_dots)
        pygame.display.update()
        fps_clock.tick(30)


def draw_cardioid(canvas, max_dots):

    canvas.fill((0, 0, 0))
    start_x = canvas.get_width() // 2
    start_y = canvas.get_height() // 2
    radius = 250

    for i in range(max_dots):
        radian = (math.pi / 180) * (360 / max_dots) * i
        sx = start_x + int(math.cos(radian) * radius)
        sy = start_y + int(math.sin(radian) * radius)

        ex = start_x + int(math.cos(radian * 2) * radius)
        ey = start_y + int(math.sin(radian * 2) * radius)

        pygame.draw.line(canvas, (0, 255, 0), (sx, sy), (ex, ey))


if __name__ == '__main__':
    main()

100개의 점을 사용한 경우
200개의 점을 사용한 경우
300개의 점을 사용한 경우

'Coding > Python 삽질기' 카테고리의 다른 글

[SQL] BEGIN TRANSACTION  (0) 2024.03.07
[Python] PNG to ICO 변환 하기  (0) 2024.01.04
[Python] 프랙탈 나무 만들기  (0) 2023.09.15
Posted by chobocho
Coding/Python 삽질기2024. 1. 4. 00:01
import sys

from PIL import Image


def convert_png_to_ico(png_path, ico_path, size=128):
    icon_size = (size, size)
    img = Image.open(png_path)
    img = img.resize(size=icon_size)
    img.save(ico_path)


def print_icon_file_info(ico_path):
    ico_image = Image.open(ico_path)
    print(f"Image type: {ico_image.format}\nSize: {ico_image.size}")


def main(source_file, target_file, icon_size=128):
    allowed_icon_size = (16, 32, 64, 128, 256)
    if icon_size not in allowed_icon_size:
        print("Error: Invalid icon size.\nAllowed size = 16, 32, 64, 128, 56\n")
        return

    convert_png_to_ico(source_file, target_file, size=icon_size)
    print_icon_file_info(target_file)


if __name__ == '__main__':
    if len(sys.argv) == 3:
        main(sys.argv[1], f"{sys.argv[1]}.ico", int(sys.argv[2]))
    elif len(sys.argv) == 2:
        main(sys.argv[1], f"{sys.argv[1]}.ico")
    else:
        print("Usage: ImageFileName [size]\n")

'Coding > Python 삽질기' 카테고리의 다른 글

Cardioid 그리기  (0) 2024.02.17
[Python] 프랙탈 나무 만들기  (0) 2023.09.15
[Python] Python 소스 코드 빌드 해보기  (1) 2023.09.06
Posted by chobocho
Coding/Tip2023. 9. 19. 23:37

1. 파일 인코딩 변경 하기

우측 하단의 UTF-8 과 같은 파일 인코딩 부분을 클릭하면 바꿀수 있다.

 

2. 줄 구분 기호 변경 하기

우측 하단의 CRLF와 같은 줄 구분 기호 부분을 클릭하면 바꿀수 있다.

Posted by chobocho