>  기사  >  백엔드 개발  >  python+pygame 간단한 스케치패드 구현 코드 예제를 살펴보겠습니다.

python+pygame 간단한 스케치패드 구현 코드 예제를 살펴보겠습니다.

coldplay.xixi
coldplay.xixi앞으로
2020-08-07 15:58:182718검색

python+pygame 간단한 스케치패드 구현 코드 예제를 살펴보겠습니다.

질문: 파이게임은 더 이상 사용되지 않나요?

오래된 것인지 아닌지 모르겠습니다. 어쨌든, 이 내용은 거의 4년 동안 공식적으로 업데이트되지 않았습니다. (다른 유사한 프로젝트에 비해) 사용하시는 분들이 꽤 많지만, 다들 재미삼아 소소한 글을 쓰는데 사용하고, 상업적인 프로젝트에 사용하시는 분들은 없습니다. Pygame은 실제로 SDL의 Python 바인딩이고 SDL은 OpenGL을 기반으로 하기 때문에 일부 사람들은 pygame+pyOpenGL을 사용하여 3D 데모 등을 수행합니다. 정말로 게임을 작성하고 싶다면 파이게임의 캡슐화는 상대적으로 낮은 수준이고 별로 유용하지 않습니다. 많은 것을 직접 구현해야 합니다(물론 자유도도 높습니다). 문서도 썩 좋지는 않지만 다행히 선배님들이 많은 글을 남겨주셨습니다. 연습용으로 좋은 선택입니다. 2D 게임에서 흔히 사용되는 많은 아이디어와 알고리즘을 연습하는 데 사용할 수 있습니다. 2D 게임을 작성하는 데 직접 사용하려면 cocos2D를 선택할 수도 있습니다(iOS API가 아니라 Python API라는 점에 유의하세요). 이 API는 매우 잘 설계되었으며 사용하기 쉽습니다. 장면 관리, 내장 콘솔 등도 있습니다. 1년동안 업데이트가 안되어서 아쉽네요... 작성자님이 업데이트 된다고 하긴 했지만, 아무래도 Objective-C 버전의 cocos에 중점을 두신거 같네요.. .프레임 애니메이션 등의 기능이 없다는 점이 아쉽습니다(Objective-C 버전에는 있습니다 T_T). 엔진을 작성하고 싶다면 pyglet을 사용해 볼 수 있습니다. 3D를 작성하고 싶다면 panda3D나 python-orge를 사용해 보세요. 저는 둘 다 사용해 본 적이 없지만 다들 그렇게 말하니 틀린 말은 아닙니다. 일반적으로 Python을 사용하여 게임을 작성하는 사람은 거의 없습니다. 작성을 마친 후에도 다른 사람들이 플레이하고 패키징하고 다양한 버그가 있을 수 있도록 환경을 설치해야 합니다. Python을 사용하여 게임에서 특정 알고리즘을 테스트하는 것은 괜찮습니다. 게임을 하고 프로토타입을 만듭니다. 실제로 쓰는 것을 잊어버리는 것이 좋습니다. 물론, 주요 질문은 저는 게임을 작성하는 데 파이게임을 전혀 사용할 계획이 없다는 것입니다. 그냥 아무 말도 하지 않은 척 하세요...

관련 학습 권장 사항: python 비디오 튜토리얼

(The 위 답변은 Zhihu 님의 답변입니다. 감사합니다!)

다음은 작화판 스크린샷입니다

# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import math
class Brush:
  def __init__(self, screen):
    self.screen = screen
    self.color = (0, 0, 0)
    self.size = 1
    self.drawing = False
    self.last_pos = None
    self.style = True
    self.brush = pygame.image.load("images/brush.png").convert_alpha()
    self.brush_now = self.brush.subsurface((0, 0), (1, 1)) 
  def start_draw(self, pos):
    self.drawing = True
    self.last_pos = pos 
  def end_draw(self):
    self.drawing = False 
  def set_brush_style(self, style):
    print("* set brush style to", style)
    self.style = style 
  def get_brush_style(self):
    return self.style 
  def get_current_brush(self):
    return self.brush_now 
  def set_size(self, size):
    if size < 1:
      size = 1
    elif size > 32:
      size = 32
    print("* set brush size to", size)
    self.size = size
    self.brush_now = self.brush.subsurface((0, 0), (size*2, size*2)) 
  def get_size(self):
    return self.size 
  def set_color(self, color):
    self.color = color
    for i in xrange(self.brush.get_width()):
      for j in xrange(self.brush.get_height()):
        self.brush.set_at((i, j),
                 color + (self.brush.get_at((i, j)).a,)) 
  def get_color(self):
    return self.color 
  def draw(self, pos):
    if self.drawing:
      for p in self._get_points(pos):
        if self.style:
          self.screen.blit(self.brush_now, p)
        else:
          pygame.draw.circle(self.screen, self.color, p, self.size)
      self.last_pos = pos
 
  def _get_points(self, pos):
    points = [(self.last_pos[0], self.last_pos[1])]
    len_x = pos[0] - self.last_pos[0]
    len_y = pos[1] - self.last_pos[1]
    length = math.sqrt(len_x**2 + len_y**2)
    step_x = len_x / length
    step_y = len_y / length
    for i in xrange(int(length)):
      points.append((points[-1][0] + step_x, points[-1][1] + step_y))
    points = map(lambda x: (int(0.5 + x[0]), int(0.5 + x[1])), points)
    return list(set(points)) 
class Menu:
  def __init__(self, screen):
    self.screen = screen
    self.brush = None
    self.colors = [
      (0xff, 0x00, 0xff), (0x80, 0x00, 0x80),
      (0x00, 0x00, 0xff), (0x00, 0x00, 0x80),
      (0x00, 0xff, 0xff), (0x00, 0x80, 0x80),
      (0x00, 0xff, 0x00), (0x00, 0x80, 0x00),
      (0xff, 0xff, 0x00), (0x80, 0x80, 0x00),
      (0xff, 0x00, 0x00), (0x80, 0x00, 0x00),
      (0xc0, 0xc0, 0xc0), (0xff, 0xff, 0xff),
      (0x00, 0x00, 0x00), (0x80, 0x80, 0x80),
    ]
    self.colors_rect = []
    for (i, rgb) in enumerate(self.colors):
      rect = pygame.Rect(10 + i % 2 * 32, 254 + i / 2 * 32, 32, 32)
      self.colors_rect.append(rect)
    self.pens = [
      pygame.image.load("images/pen1.png").convert_alpha(),
      pygame.image.load("images/pen2.png").convert_alpha(),
    ]
    self.pens_rect = []
    for (i, img) in enumerate(self.pens):
      rect = pygame.Rect(10, 10 + i * 64, 64, 64)
      self.pens_rect.append(rect)
    self.sizes = [
      pygame.image.load("images/big.png").convert_alpha(),
      pygame.image.load("images/small.png").convert_alpha()
    ]
    self.sizes_rect = []
    for (i, img) in enumerate(self.sizes):
      rect = pygame.Rect(10 + i * 32, 138, 32, 32)
      self.sizes_rect.append(rect)
 
  def set_brush(self, brush):
    self.brush = brush
 
  def draw(self):
    for (i, img) in enumerate(self.pens):
      self.screen.blit(img, self.pens_rect[i].topleft)
    for (i, img) in enumerate(self.sizes):
      self.screen.blit(img, self.sizes_rect[i].topleft)
    self.screen.fill((255, 255, 255), (10, 180, 64, 64))
    pygame.draw.rect(self.screen, (0, 0, 0), (10, 180, 64, 64), 1)
    size = self.brush.get_size()
    x = 10 + 32
    y = 180 + 32
    if self.brush.get_brush_style():
      x = x - size
      y = y - size
      self.screen.blit(self.brush.get_current_brush(), (x, y))
    else:
      pygame.draw.circle(self.screen,
                self.brush.get_color(), (x, y), size)
    for (i, rgb) in enumerate(self.colors):
      pygame.draw.rect(self.screen, rgb, self.colors_rect[i])
  def click_button(self, pos):
    for (i, rect) in enumerate(self.pens_rect):
      if rect.collidepoint(pos):
        self.brush.set_brush_style(bool(i))
        return True
    for (i, rect) in enumerate(self.sizes_rect):
      if rect.collidepoint(pos):
        if i:
          self.brush.set_size(self.brush.get_size() - 1)
        else:
          self.brush.set_size(self.brush.get_size() + 1)
        return True
    for (i, rect) in enumerate(self.colors_rect):
      if rect.collidepoint(pos):
        self.brush.set_color(self.colors[i])
        return True
    return False
class Painter:
  def __init__(self):
    self.screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("Painter")
    self.clock = pygame.time.Clock()
    self.brush = Brush(self.screen)
    self.menu = Menu(self.screen)
    self.menu.set_brush(self.brush)
  def run(self):
    self.screen.fill((255, 255, 255))
    while True:
      self.clock.tick(30)
      for event in pygame.event.get():
        if event.type == QUIT:
          return
        elif event.type == KEYDOWN:
          if event.key == K_ESCAPE:
            self.screen.fill((255, 255, 255))
        elif event.type == MOUSEBUTTONDOWN:
          if event.pos[0] <= 74 and self.menu.click_button(event.pos):
            pass
          else:
            self.brush.start_draw(event.pos)
        elif event.type == MOUSEMOTION:
          self.brush.draw(event.pos)
        elif event.type == MOUSEBUTTONUP:
          self.brush.end_draw()
      self.menu.draw()
      pygame.display.update()
def main():
  app = Painter()
  app.run()
 
if __name__ == &#39;__main__&#39;:
  main()

위 내용은 python+pygame 간단한 스케치패드 구현 코드 예제를 살펴보겠습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 jb51.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제