logo

Python으로 게임을 개발하는 방법

가장 적응성이 뛰어난 언어는 Python으로, 게임 개발, 웹 개발, 기계 학습, 인공 지능, GUI 애플리케이션 등 거의 모든 산업에서 사용됩니다.

이 게임은 Python에 내장된 기능인 pygame 패키지를 사용하여 개발되었습니다. Python 프로그래밍에 대한 기초적인 이해를 바탕으로 파이게임 모듈을 활용하여 적절한 애니메이션, 음향 효과 및 음악을 갖춘 시각적으로 매력적인 게임을 만들 수 있습니다.

Pygame이라는 크로스 플랫폼 라이브러리는 비디오 게임을 만드는 데 사용됩니다. 플레이어에게 일반적인 게임 경험을 제공하는 사운드 라이브러리와 컴퓨터 영상이 있습니다.

Pete Shinners는 PySDL을 대체하기 위해 이를 개발하고 있습니다.

파이게임의 전제 조건

Pygame을 배우려면 Python 프로그래밍 언어를 이해해야 합니다.

1000.00개 중 1개

파이게임 설치

Pygame을 설치하려면 명령줄 터미널을 열고 다음 명령을 입력하세요.

 pip install pygame 

IDE를 통해서도 설치할 수 있습니다. 추가 설치 안내를 보려면 전체 파이게임 튜토리얼( https://www.javatpoint.com/pygame )을 방문하세요. 여기서는 필수적인 파이게임 설명을 모두 찾을 수 있습니다.

간단한 파이게임 예제

다음은 간단한 파이게임 창을 만드는 예입니다.

 import pygame pygame.init() screen = pygame.display.set_mode((400,500)) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.flip() 

산출:

문자열 비교 자바
Python으로 게임을 개발하는 방법

설명:

제공된 코드는 400x500픽셀의 파이게임 창을 열고 항상 이벤트를 감시하는 루프를 시작합니다. 루프는 'done' 변수를 True로 변경하여 QUIT 이벤트가 감지되면(보통 사용자가 창을 종료할 때) 루프를 종료하고 프로그램을 종료합니다. 디스플레이를 업데이트하고 'pygame.display.flip()' 메서드 덕분에 모든 변경 사항이 화면에 표시되는지 확인합니다. 간단히 말하면, 코드는 사용자가 닫을 때까지 활성 상태를 유지하는 작은 파이게임 창을 생성하여 이벤트 중심의 기본 프로그램 구조를 보여줍니다.

모든 그래픽은 파이게임 창에 그려집니다.

위 프로그램의 기본 구문을 이해해 봅시다.

    파이게임 가져오기:파이게임의 모든 기능에 접근할 수 있게 해주는 모듈이다.열():파이게임에 필요한 각 모듈을 초기화하는 데 사용됩니다.display.set_mode((너비, 높이)):창 크기를 조정하는 데 사용됩니다. 그것은 표면에 있는 아이템을 돌려줄 것입니다. 그래픽 작업은 표면 개체를 통해 수행됩니다.이벤트.get():결과는 빈 이벤트 큐입니다. 호출하지 않으면 운영 체제는 게임이 응답하지 않는 것으로 인식하고 창 메시지가 누적되기 시작합니다.그만두다:창 모서리에 있는 십자 버튼을 클릭하면 이벤트를 해제하는 데 사용됩니다.디스플레이.플립():게임에 대한 모든 업데이트가 여기에 반영됩니다. 변경할 때마다 디스플레이에 접속해야 합니다.flip()은 함수입니다.

아름다운 글꼴과 그림을 포함하여 어떤 형태든 파이게임 표면에 그릴 수 있습니다. 파이게임에 내장된 다양한 메소드를 사용하면 화면에 기하학적 모양을 그릴 수 있습니다. 이러한 양식은 게임 제작의 첫 번째 단계를 나타냅니다.

화면에 그려지는 양식에 대한 다음 그림을 살펴보겠습니다.

컴퓨터 작업

예 -

 import pygame from math import pi pygame.init() # size variable is using for set screen size size = [400, 300] screen = pygame.display.set_mode(size) pygame.display.set_caption('Example program to draw geometry') # done variable is using as flag done = False clock = pygame.time.Clock() while not done: # clock.tick() limits the while loop to a max of 10 times per second. clock.tick(10) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked on close symbol done = True # done variable that we are complete, so we exit this loop # All drawing code occurs after the for loop and but # inside the main while done==False loop. # Clear the default screen background and set the white screen background screen.fill((0, 0, 0)) # Draw on the screen a green line which is 5 pixels wide. pygame.draw.line(screen, (0, 255, 0), [0, 0], [50, 30], 5) # Draw on the screen a green line which is 5 pixels wide. pygame.draw.lines(screen, (0, 0, 0), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5) # Draw a rectangle outline pygame.draw.rect(screen, (0, 0, 0), [75, 10, 50, 20], 2) # Draw a solid rectangle pygame.draw.rect(screen, (0, 0, 0), [150, 10, 50, 20]) # This draw an ellipse outline, using a rectangle as the outside boundaries pygame.draw.ellipse(screen, (255, 0, 0), [225, 10, 50, 20], 2) # This draw a solid ellipse, using a rectangle as the outside boundaries pygame.draw.ellipse(screen, (255, 0, 0), [300, 10, 50, 20]) # Draw a triangle using the polygon function pygame.draw.polygon(screen, (0, 0, 0), [[100, 100], [0, 200], [200, 200]], 5) # This draw a circle pygame.draw.circle(screen, (0, 0, 255), [60, 250], 40) # This draw an arc pygame.draw.arc(screen, (0, 0, 0), [210, 75, 150, 125], 0, pi / 2, 2) # This function must write after all the other drawing commands. pygame.display.flip() # Quite the execution when clicking on close pygame.quit() 

산출:

네트워킹 및 유형
Python으로 게임을 개발하는 방법

설명:

주어진 Python 프로그램은 Pygame 패키지를 사용하여 다양한 기하학적 모양이 그려진 그래픽 창을 만듭니다. 프로그램은 400x300 픽셀의 파이게임 창을 생성한 다음 항상 이벤트를 감시하는 루프를 시작하여 사용자가 종료할 때까지 창이 열려 있는지 확인합니다. 이 루프가 시작될 때 화면을 지운 다음 Pygame의 그리기 루틴을 사용하여 다양한 색상과 선 너비로 다양한 형태를 만듭니다. 이러한 모양에는 선, 다각형, 타원, 원 및 호가 포함됩니다. 모든 양식에는 적절한 좌표와 속성이 정의되어 있습니다. 마지막으로 'pygame.display.flip()'을 사용하여 디스플레이를 새로 고칩니다. 프로그램은 창이 닫힐 때 파이게임을 종료합니다.

이 응용 프로그램은 Pygame의 그리기 기능의 적응성과 다양성을 보여주는 예이며 대화형 그래픽 응용 프로그램을 개발하기 위한 프레임워크를 제공합니다. 개발자는 좌표, 색상, 선 너비와 같은 매개변수를 조정하여 Pygame의 그래픽 환경 내에서 광범위한 시각적 구성 요소를 만들 수 있습니다. 이를 통해 대화형 멀티미디어 애플리케이션, 게임 및 시뮬레이션을 구축할 수 있습니다.

예 - Pygame을 사용하여 뱀 게임 개발

프로그램 -

 # Snake Tutorial Using Pygame import math import random import pygame import tkinter as tk from tkinter import messagebox class cube(object): rows = 20 w = 500 def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self, dirnx, dirny): self.dirnx = dirnx self.dirny = dirny self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny) def draw(self, surface, eyes=False): dis = self.w // self.rows i = self.pos[0] j = self.pos[1] pygame.draw.rect(surface, self.color, (i * dis + 1, j * dis + 1, dis - 2, dis - 2)) if eyes: centre = dis // 2 radius = 3 circleMiddle = (i * dis + centre - radius, j * dis + 8) circleMiddle2 = (i * dis + dis - radius * 2, j * dis + 8) pygame.draw.circle(surface, (0, 0, 0), circleMiddle, radius) pygame.draw.circle(surface, (0, 0, 0), circleMiddle2, radius) # This class is defined for snake design and its movement class snake(object): body = [] turns = {} def __init__(self, color, pos): self.color = color self.head = cube(pos) self.body.append(self.head) self.dirnx = 0 self.dirny = 1 def move(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() keys = pygame.key.get_pressed() # It will manage the keys movement for the snake for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] # Snake when hit the boundary wall for i, c in enumerate(self.body): p = c.pos[:] if p in self.turns: turn = self.turns[p] c.move(turn[0], turn[1]) if i == len(self.body) - 1: self.turns.pop(p) else: if c.dirnx == -1 and c.pos[0] = c.rows - 1: c.pos = (0, c.pos[1]) elif c.dirny == 1 and c.pos[1] &gt;= c.rows - 1: c.pos = (c.pos[0], 0) elif c.dirny == -1 and c.pos[1] <= 0 1 0: c.pos="(c.pos[0]," c.rows - 1) else: c.move(c.dirnx, c.dirny) def reset(self, pos): self.head="cube(pos)" self.body="[]" self.body.append(self.head) self.turns="{}" self.dirnx="0" self.dirny="1" # it will add the new cube in snake tail after every successful score addcube(self): dx, dy="tail.dirnx," tail.dirny if dx="=" and self.body.append(cube((tail.pos[0] 1, tail.pos[1]))) elif -1 + 1: self.body.append(cube((tail.pos[0], tail.pos[1] 1))) -1: self.body[-1].dirnx="dx" self.body[-1].dirny="dy" draw(self, surface): for i, c enumerate(self.body): i="=" c.draw(surface, true) c.draw(surface) drawgrid(w, rows, sizebtwn="w" rows x="0" y="0" l range(rows): draw grid line pygame.draw.line(surface, (255, 255, 255), (x, 0), w)) (0, y), (w, y)) this class define game surface redrawwindow(surface): global width, s, snack is used to surface.fill((0, 0, 0)) s.draw(surface) snack.draw(surface) drawgrid(width, surface) pygame.display.update() randomsnack(rows, item): positions="item.body" while true: len(list(filter(lambda z: z.pos="=" positions)))> 0: continue else: break return (x, y) # Using Tkinter function to display message def message_box(subject, content): root = tk.Tk() root.attributes(&apos;-topmost&apos;, True) root.withdraw() messagebox.showinfo(subject, content) try: root.destroy() except: pass # main() function def main(): global width, rows, s, snack width = 500 rows = 20 win = pygame.display.set_mode((width, width)) s = snake((255, 0, 0), (10, 10)) snack = cube(randomSnack(rows, s), color=(0, 255, 0)) flag = True clock = pygame.time.Clock() while flag: pygame.time.delay(50) clock.tick(10) s.move() if s.body[0].pos == snack.pos: s.addCube() snack = cube(randomSnack(rows, s), color=(0, 255, 0)) for x in range(len(s.body)): if s.body[x].pos in list(map(lambda z: z.pos, s.body[x + 1:])): print(&apos;Score: 
&apos;, len(s.body)) message_box(&apos;You Lost!
&apos;, &apos;Play again...
&apos;) s.reset((10, 10)) break redrawWindow(win) pass main() </=>

산출:

Python으로 게임을 개발하는 방법

뱀이 자신과 접촉하면 게임이 종료되고 다음 메시지가 표시됩니다.

자바를 인쇄하는 방법
Python으로 게임을 개발하는 방법

다시 시작하려면 확인 버튼을 클릭하기만 하면 됩니다. Pycharm 터미널에 점수가 표시됩니다(우리는 Pycharm IDE를 사용했지만 Python IDE를 사용해도 됩니다).

Python으로 게임을 개발하는 방법

설명:

제공된 Python 스크립트는 Pygame 패키지를 사용하여 간단한 Snake 게임을 만듭니다. 스네이크와 그 몸체를 구성하는 별도의 큐브 모두에 ​​대한 클래스를 설정합니다. 파이게임은 격자 구조와 움직이는 뱀이 특징인 게임 창을 설정하는 데 사용됩니다. '간식' 큐브를 먹은 후 뱀은 길이가 길어지고, 자신이나 경계벽에 부딪히면 게임이 종료됩니다.

뱀의 방향을 관리하고, 그리드의 임의 지점에서 스낵을 생성하고, 뱀의 머리와 몸 사이의 충돌을 감지하고, 게임 상태를 업데이트하고, 게임 창을 다시 그리려면 게임 로직이 사용자 입력을 처리해야 합니다. 게임 상호 작용과 시각적 업데이트를 제어하기 위해 스크립트는 Pygame의 이벤트 처리 및 그리기 방법을 사용합니다. 또한 Tkinter를 사용하여 플레이어가 게임에서 패배했을 때와 같은 메시지를 표시하는 기본 메시지 상자 기능도 있습니다. 전반적으로 이 스크립트는 파이게임 게임 프로그래밍의 핵심 아이디어를 보여주고 빈티지 스네이크 게임의 기초적인 표현을 제공합니다.