본문 바로가기

Python/파이썬 프로젝트

[파이썬 미니 프로젝트] Pyautogui로 미로찾기 게임 수행하기

한국교원대 복수전공 과제. 백워드 설계로 교육자료 만들기

수행자 : 성원경, 김한길 선생님, 이윤우 선생님, 김희연 선생님 ★

과제 자료 : 

백워드설계(알고리즘과프로그래밍_김희연, 김한길, 성원경, 이윤우) 최종.hwp
0.07MB

 

기본 과제 목표 : 파이썬 매크로를 활용하여 미로게임 자동화 해결하기

(테스트 장소 : 교원대 쪽문 CU 편의점 벤치)

기본 조건 : pyautogui 모듈을 활용하여 미로게임을 자동화 수행 프로그램 작성

 

사전학습 리뷰 : 파이썬 매크로 소개와 기본 프로젝트 수행

https://pythonkorea.com/23

 

[모듈 2-12] 파이썬 매크로 기본 함수와 다양한 활용 예제 코드

1. 파이썬 매크로 기본 함수 배우기 - 메모장에 마음대로 낙서하기 ### intro. ## Date : 2020. 11. 26 ## Editer : 성원경 선생님 / 경기기계공업고등학교 ### 1. 파이썬 기본 매크로 함수 사용하기 import pyautogu

pythonkorea.com

 

 

미로게임 출처 

1) 웹기반 게임 사용

https://ko.y8.com/games/maze_escape

 

게임 Maze - 온라인 플레이: Y8.com

Y8.com에서 무료 게임 Maze(을)를 플레이하십시오! Maze 을(를) 플레이하려면 Click now를 클릭하십시오! Maze(와)과 비슷한 최고의 게임들을 즐기십시오.

ko.y8.com

 

2) 깃허브 오픈소스

https://github.com/StanislavPetrovV/Maze_Game

 

GitHub - StanislavPetrovV/Maze_Game: Maze Game using Pygame

Maze Game using Pygame. Contribute to StanislavPetrovV/Maze_Game development by creating an account on GitHub.

github.com

 

샘플 코드

from pyautogui import *
from time import sleep

delay = 0.5
hotkey("alt", "tab")
sleep(delay)
press('up')
sleep(delay)
press('left')
sleep(delay)
press('up')
sleep(delay)
press('left')
sleep(delay)
press('right')
sleep(delay)
press('up')
sleep(delay)
press('right')

 

 

평가기준 

1) 코드의 확장성 : 다른 미로게임이나 다른 종류의 게임에서도 코드가 최소한 수정으로 동작 되는가?

2) 소프트웨어의 독창성 : 소프트웨어 구동, UI 등에 차별점을 두었는가?

3) 문제해결과정의 기록 : 소프트웨어를 제작하면서 발생한 문제 해결과정을 잘 기록하고 이에 대한 다양한 해결 방법을 접근 했는가?

4) 다양한 협업 : 외부 오픈소스, ChatGPT, API, 동료와의 협업 등 외부의 도움을 받아 자신의 소프트웨어 제작에 질적 성장을 이루어 냈는가?

5) 소프트웨어의 확장성 : 해당 프로젝트를 배포 할 수 있는 플랫폼 ( exe 파일 또는 웹호스팅 등)에 대한 고민을 하였는가? 또는 해당 프로젝트를 확장시켜 실제 사업화 할 수 있는 아이디어가 있는가?

 

 

 

과제 제출 방법 : 문제해결 과정과 결과를 담은 OPP(Online project Portfolio)

 

예시 : 노션 & 유튜브(2022년 경기기계공업고 항공드론 수업 예시)

https://organic-fontina-944.notion.site/2-d0cb94a3953a4d52bb6f763ec0723c14

 

2학년 항공드론 [뒷분반]

[ 1학기 ]

organic-fontina-944.notion.site

 

 

예시 : 구글 사이트 도구(2022년 경기기계공업고 2학년 신00 학생 제출 자료)

https://sites.google.com/sonline20.sen.go.kr/pgm/main?authuser=0 

 

PGM

PGM

sites.google.com

 

 

예시 : 캔바(음성인식 로봇팔 제작과정 자료)

https://www.canva.com/design/DAFnqqr5ghc/E5VpJlCQzuB7OfziypYJMQ/view?utm_content=DAFnqqr5ghc&utm_campaign=designshare&utm_medium=link&utm_source=publishsharelink 

 

 

 

원한다면 심화 & 도전 포인트 : 오픈소스 인공지능 모델 + 파이썬 매크로 + 게임

 

ex) 인공지능 오픈소스 모델 미디어파이프 

https://mediapipe-studio.webapps.google.com/home

 

ex) 미디어파이프 오픈소스 모델 활용 사례 깃허브

https://github.com/AslanDevbrat/gesture_VidGame

 

GitHub - AslanDevbrat/gesture_VidGame: Gesture-controlled Video Game. Just swing your finger and play the game without touching

Gesture-controlled Video Game. Just swing your finger and play the game without touching your PC - GitHub - AslanDevbrat/gesture_VidGame: Gesture-controlled Video Game. Just swing your finger and p...

github.com

 

ex) 실제 게임에 연결 사례

1) 크롬 공룡 게임과 연결사례

 

2) 슈퍼마리오 게임과 연결 사례

 

인공지능 제어 샘플코드

import cv2
import mediapipe
import time
import pyautogui
import threading

ctime = 0
ptime = 0
last_press_time = 0
delay_time = 0.05 # Delay time in seconds

cap = cv2.VideoCapture(0)

def handle_keys(fingercount):  
    global last_press_time  # 이 부분을 추가
    if (fingercount == 1 or fingercount == 2)and time.time() - last_press_time > delay_time:
                            pyautogui.press('space')
                            last_press_time = time.time() # Record the time of the press

    if fingercount == 5:
        pyautogui.keyDown('down')
    else:
        pyautogui.keyUp('down')


medhands = mediapipe.solutions.hands
hands = medhands.Hands(max_num_hands=1, min_detection_confidence=0.7)
draw = mediapipe.solutions.drawing_utils

while True:
    success, img = cap.read()
    img = cv2.flip(img, 1)
    imgrgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    res = hands.process(imgrgb)

    lmlist = []
    tipids = [4, 8, 12, 16, 20]

    cv2.rectangle(img, (20, 350), (90, 440), (0, 255, 204), cv2.FILLED)
    cv2.rectangle(img, (20, 350), (90, 440), (0, 0, 0), 5)

    if res.multi_hand_landmarks:
        for handlms in res.multi_hand_landmarks:
            for id, lm in enumerate(handlms.landmark):

                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                lmlist.append([id, cx, cy])
                if len(lmlist) != 0 and len(lmlist) == 21:
                    fingerlist = []

                    # Thumb and dealing with flipping of hands
                    if lmlist[12][1] > lmlist[20][1]:
                        if lmlist[tipids[0]][1] > lmlist[tipids[0] - 1][1]:
                            fingerlist.append(1)
                        else:
                            fingerlist.append(0)
                    else:
                        if lmlist[tipids[0]][1] < lmlist[tipids[0] - 1][1]:
                            fingerlist.append(1)
                        else:
                            fingerlist.append(0)

                    # Others
                    for id in range(1, 5):
                        if lmlist[tipids[id]][2] < lmlist[tipids[id] - 2][2]:
                            fingerlist.append(1)
                        else:
                            fingerlist.append(0)

                    if len(fingerlist) != 0:
                        fingercount = fingerlist.count(1)
                        threading.Thread(target=handle_keys, args=(fingercount,)).start()


                        # If only one finger is detected and enough time has passed, press the space bar
                             
                        # if fingercount   == 5 :
                        #     pyautogui.keyDown('down')
                            
                        # else : pyautogui.keyUp(       'down')


                    cv2.putText(img, str(fingercount), (25, 430), cv2.FONT_HERSHEY_PLAIN, 6, (0, 0, 0), 5)

                # Change color of points and lines
                draw.draw_landmarks(img, handlms, medhands.HAND_CONNECTIONS,
                                    draw.DrawingSpec(color=(0, 255, 204), thickness=2, circle_radius=2),
                                    draw.DrawingSpec(color=(0, 0, 0), thickness=2, circle_radius=3))

    # FPS counter
    ctime = time.time()
    fps = 1 / (ctime - ptime)
    ptime = ctime

    # FPS display
    cv2.putText(img, f'FPS:{str(int(fps))}', (0, 12), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 1)

    cv2.imshow("hand gestures", img)

    # Press q to quit
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()

 

GPT와 협업은 이제 선택이 아닌 필수...

https://chat.openai.com/share/1e52baef-943c-4b14-8311-7ed6494173fe

 

ChatGPT

A conversational AI system that listens, learns, and challenges

chat.openai.com

 

 

 

발표를 마치며. 

Q. 우리는 무엇을 위해 학생들에게 정보컴퓨터 교육을 하는가?

 

 

 

힌트.

 

 

 

 

함께 하는 즐거움

 

선생님들께 하고싶으말......

더보기

모두 고생 많으셨습니다. 6개월간 한분한분 모두 배려해주시고 열심히 해주셔서 잘 마칠 수 있었습니다. 감사합니다.

 

2023학년도 한국교원대 정보컴퓨터 복수전공 끝.

 

 

 

@WONKING2023