머신러닝

본문 바로가기
사이트 내 전체검색


머신러닝
머신러닝

5. pygame 예제 - 회전

페이지 정보

작성자 관리자 댓글 0건 조회 1,101회 작성일 21-02-17 08:25

본문

5. pygame 예제 - 회전

예제 1.


import pygame as py  


# define constants  

WIDTH = 500  

HEIGHT = 500  

FPS = 200


# define colors  

BLACK = (0 , 0 , 0)  

GREEN = (0 , 255 , 0)


# initialize pygame and create screen  

py.init()  

screen = py.display.set_mode((WIDTH , HEIGHT))  

# for setting FPS  

clock = py.time.Clock()  


rot = 0  

rot_speed = .2  


# define a surface (RECTANGLE)  

image_orig = py.Surface((1 , 100))  

# for making transparent background while rotating an image  

image_orig.set_colorkey(BLACK)  

# fill the rectangle / surface with green color  

image_orig.fill(GREEN)  

# creating a copy of orignal image for smooth rotation  

image = image_orig.copy()  

image.set_colorkey(BLACK)  

# define rect for placing the rectangle at the desired position  

rect = image.get_rect()

x, y = py.mouse.get_pos()

rect.center = (x, y)  

# keep rotating the rectangle until running is set to False


running = True  

while running:  


    x, y = py.mouse.get_pos()

    # set FPS  

    clock.tick(FPS)  

    # clear the screen every time before drawing new objects  

    screen.fill(BLACK)  

    # check for the exit  

    for event in py.event.get():  

        if event.type == py.QUIT:  

            running = False


    # rotating the orignal image

    keys = py.key.get_pressed()

    if keys[py.K_a]:

        rot_speed = .2 

    if keys[py.K_d]:

        rot_speed = -.2 


    # defining angle of the rotation  

    rot = (rot + rot_speed) % 360  # 이미지의 새로운 각도를 계산합니다 :

    # rotating the orignal image

    image = py.transform.rotate(image_orig, rot)  

    rect = image.get_rect(center = (x, y))  

    # drawing the rotated rectangle to the screen  

    screen.blit(image, rect)  

    # flipping the display after drawing everything  

    py.display.flip()


py.quit() 


예제 2.

- 스페이스 바로 돌림판의 회전과 정지를 정함

- 정지 시 천천히 멈춤 (회전각을 0까지 빼줌)


# -*- coding: utf-8 -*-

import sys

import pygame

from pygame.locals import *

import time

 

# 초당 프레임수를 정의

TARGET_FPS = 30

clock = pygame.time.Clock()

 

# 색 정의

BLACK = (0, 0, 0)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

WHITE = (255, 255, 255)

 

# 라이브러리 및 디스플레이 초기화

pygame.init()

screen = pygame.display.set_mode((600, 400), DOUBLEBUF) # 윈도우 크기 및 속성 설정

pygame.display.set_caption('돌림판')  # 타이틀바의 텍스트를 설정

 

# 이미지 파일을 로딩

img = pygame.image.load('images.png') # 돌림판 이미지

img2 = pygame.image.load('images2.jpg') # 화살표

 

degree = 0

flag = True 

rad = 100

stop_time = 3 # 돌림판이 멈출 때까지의 시간 (클수록 빨리 멈춤)

 

# 메인 루프

while True:

  for event in pygame.event.get():

    # 이벤트를 처리하는 부분

    if event.type == QUIT:

      pygame.quit()

      sys.exit()

 

    # 키보드 이벤트 처리

    if event.type == KEYDOWN:

      # 스페이스 -> 토글

      if event.key == 32:

          if flag == True:

              flag = False

          elif flag == False:

              flag = True

              rad = 100

 

  # 게임의 상태를 화면에 그려주는 부분

  screen.fill(WHITE)

  

  # 이미지 파일 회전하여 그리기

  x = 350

  y = 200

  

  rotated = pygame.transform.rotate(img, degree) # degree 만큼 회전

  rect = rotated.get_rect()

  rect.center = (x, y)

  screen.blit(rotated, rect)

 

  # 플래그의 상태가 True면 회전, False면 천천히 정지

  if flag == True:

      degree += rad

  elif flag == False:

      if rad > 0:

          rad -= stop_time

          degree += rad

          

 

  screen.blit(img2, (70, 180)) # 화살표 그리기

  pygame.display.flip()  # 화면 전체를 업데이트

  clock.tick(TARGET_FPS)  # 프레임 수 맞추기



예제 3.

import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
# The normal image/pygame.Surface.
player_image = pygame.Surface((30, 50), pygame.SRCALPHA)
player_image.fill((0, 100, 200))
pygame.draw.circle(player_image, (0, 50, 100), (15, 20), 12)
# The rotated image.
player_rotated = pygame.transform.rotate(player_image, 60)

FPS = 60

def gameLoop():
player = player_image
player_pos = [100, 223]
gameExit = False

while gameExit == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
# Assign the current image to the `player` variable.
if event.key == pygame.K_UP:
player = player_image
elif event.key == pygame.K_DOWN:
player = player_rotated

gameDisplay.fill((30, 30, 30))
gameDisplay.blit(player, player_pos)

pygame.display.flip()
clock.tick(60)

gameLoop()
pygame.quit()


예제 4.

import pygame
import sys
import time
import random

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
SPAWN_TIME = 1

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

pygame.init()
pygame.display.set_caption("Stars in Space")
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()


class Star(object):
    def __init__(self):
        self.image = pygame.image.load("images/star.png").convert_alpha()
        self.x = random.randint(0, SCREEN_WIDTH - self.image.get_width())
        self.y = random.randint(0, SCREEN_HEIGHT - self.image.get_height())
        self.head = random.randint(0, 359)
        self.rotated_image = pygame.transform.rotate(self.image, self.head)
        self.rotate_speed = random.randint(1, 3)

    def rotate(self):
        self.head += self.rotate_speed
        self.rotated_image = pygame.transform.rotate(self.image, self.head)

    def draw(self):
        screen.blit(self.rotated_image, (self.x + self.image.get_width() / 2 - self.rotated_image.get_width() / 2,
                                         self.y + self.image.get_height() / 2 - self.rotated_image.get_height() / 2))


def main():
    stars = []

    last_spawn_time = time.time()

    while True:
        clock.tick(60)
        screen.fill(BLACK)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        if time.time() - last_spawn_time > SPAWN_TIME:
            stars.append(Star())
            last_spawn_time = time.time()

        for star in stars:
            star.rotate()
            star.draw()

        pygame.display.update()


if __name__ == "__main__":
    main()

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.