Python을 사용하여 간단한 게임 개발

php中世界最好的语言
풀어 주다: 2018-04-09 11:33:58
원래의
7801명이 탐색했습니다.

이번에는 Python을 사용하여 간단한 게임을 개발하는 방법을 알려드리겠습니다. Python을 사용하여 소규모 게임을 개발할 때 주의사항은 무엇인가요? 실제 사례를 살펴보겠습니다.

소개

Python 언어는 최근 과학 컴퓨팅 분야에서의 유용성 외에도 게임, 백엔드 등에서도 빛을 발하고 있습니다. 이 블로그 게시물은 공식적인 프로젝트 개발 프로세스를 따릅니다. 재미를 경험하기 위해 작은 파이썬 게임을 작성하는 방법을 단계별로 가르쳐 드리겠습니다. 이번에 개발된 게임은 에일리언 인베이젼(Alien Invasion)이라고 합니다.

pygame을 설치하고 좌우로 움직일 수 있는 우주선을 만들어 보세요

pygame 설치

내 컴퓨터는 windows 10, python3.6, pygame 다운로드 주소: Portal

해당 Python 버전의 pygame을 다운로드하고 다음 명령을 실행하세요.

$ pip install wheel
$ pip install pygame‑1.9.3‑cp36‑cp36m‑win_amd64.whl
로그인 후 복사

파이게임 창 생성 및 사용자 입력에 응답

Alien_invasion이라는 새 폴더를 생성하고 폴더에 Alien_invasion.py 파일을 새로 생성한 후 다음 코드를 입력하세요.

import sys
import pygame
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  screen = pygame.display.set_mode((1200,800))
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(bg_color)
    # visualiaze the window
    pygame.display.flip()
run_game()
로그인 후 복사

위 코드를 실행하면 회색 인터페이스가 있는 창을 얻을 수 있습니다.

$ python alien_invasion.py

설정 클래스를 만듭니다

게임 작성 과정에서 몇 가지 새로운 기능을 쉽게 만들 수 있습니다. , 다음 추가 설정 클래스를 포함하는 설정 모듈을 작성하여 모든 설정을 한 곳에 저장합니다. 이렇게 하면 나중에 프로젝트가 성장함에 따라 게임의 모양을 수정하기가 더 쉬워집니다. 먼저 Alien_invasion.py에서 디스플레이 크기와 디스플레이 색상을 수정합니다. 먼저, Alien_invasion 폴더 아래에 새로운 Python 파일 settings.py를 만들고 다음 코드를 추가합니다.

class Settings(object):
  """docstring for Settings"""
  def init(self):
    # initialize setting of game
    # screen setting
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (230,230,230)
로그인 후 복사

그런 다음 Alien_invasion.py에서 설정 클래스를 가져오고 관련 설정을 다음과 같이 수정합니다.

import sys
import pygame
from settings import Settings
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
  screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(ai_settings.bg_color)
    # visualiaze the window
    pygame.display.flip()
run_game()
로그인 후 복사

Add 우주선 이미지

다음으로 우주선을 게임에 추가해야 합니다. 화면에 플레이어의 함선을 그리기 위해 이미지를 로드하고 Pygame() 메서드 blit()을 사용하여 그립니다. 거의 모든 유형의 이미지 파일을 게임에서 사용할 수 있지만, Pygame은 기본적으로 비트맵을 로드하므로 비트맵(.bmp) 파일을 사용하는 것이 가장 쉽습니다. 다른 유형의 이미지를 로드할 수 있지만 추가 라이브러리를 설치해야 합니다. 무료 스톡 사진 사이트인 Portal에서 이미지를 찾는 것이 좋습니다. 메인 프로젝트 폴더(alien_invasion)에 이미지라는 새 폴더를 만들고 여기에 다음 bmp 그림을 넣습니다.

다음으로 선박 클래스 ship.py를 만듭니다.

import pygame
class Ship():
  def init(self,screen):
    #initialize spaceship and its location
    self.screen = screen
    # load bmp image and get rectangle
    self.image = pygame.image.load('image/ship.bmp')
    self.rect = self.image.get_rect()
    self.screen_rect = screen.get_rect()
    #put spaceship on the bottom of window
    self.rect.centerx = self.screen_rect.centerx
    self.rect.bottom = self.screen_rect.bottom
  def blitme(self):
    #buld the spaceship at the specific location
    self.screen.blit(self.image,self.rect)
로그인 후 복사

마지막으로 화면에 선박을 그립니다. 즉, Alien_invasion.py 파일에서 blitme 메서드를 호출합니다.

import sys
import pygame
from settings import Settings
from ship import Settings
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
  screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
  ship = Ship(screen)
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    # visualiaze the window
    pygame.display.flip()
run_game()
로그인 후 복사

리팩토링: 모듈 game_functions

대규모 프로젝트에서는 새 코드를 추가하기 전에 기존 코드를 리팩터링해야 하는 경우가 많습니다. 리팩토링의 목적은 코드 구조를 단순화하고 확장을 더 쉽게 만드는 것입니다. 우리는 Alien Invasion 게임을 실행할 수 있는 여러 함수를 저장하는 game_functions 모듈을 구현할 것입니다. game_functions 모듈을 생성하면 Alien_invasion.py가 너무 길어지는 것을 방지할 수 있어 논리를 더 쉽게 이해할 수 있습니다.

function check_events()

먼저 이벤트 루프를 분리하기 위해 events를 관리하는 코드를 check_events()라는 함수로 옮깁니다

import sys
import pygame
def check_events():
  #respond to keyboard and mouse item
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()
로그인 후 복사

그런 다음 Alien_invasion.py 코드를 수정하고 game_functions 모듈을 만들고 이벤트 루프를 check_events() 함수 호출로 대체합니다.

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
로그인 후 복사

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 다른 관련 항목에 주의하세요. PHP 중국어 웹사이트의 기사!

추천 도서:

파이썬이 txt 파일을 한 줄씩 읽고 쓰는 방법

파이썬이 데이터를 업데이트하기 위해 mysql을 호출하는 방법

위 내용은 Python을 사용하여 간단한 게임 개발의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!