import sys
import math
import random
import pygame
from pygame.locals import QUIT, KEYDOWN, K_LEFT, K_RIGHT, Rect

class Block:
    def __init__(self, col, rect, speed = 0):
        self.col = col
        self.rect = rect
        self.speed = speed
        self.dir = random.randint(-45, 45) + 270
    
    def move(self):
        self.rect.centerx += math.cos(math.radians(self.dir)) * self.speed
        self.rect.centery -= math.sin(math.radians(self.dir)) * self.speed
    
    def draw(self):
        if self.speed == 0:
            pygame.draw.rect(SURFACE, self.col, self.rect)
        else:
            pygame.draw.ellipse(SURFACE, self.col, self.rect)

def tick():
    global BLOCKS
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                PADDLE.rect.centerx -= 10
            elif event.key == K_RIGHT:
                PADDLE.rect.centerx += 10
    if BALL.rect.centery < 1000:
        BALL.move()

    prev_len = len(BLOCKS)
    BLOCKS = [
        x for x in BLOCKS
        if not x.rect.colliderect(BALL.rect)
    ]
    if len(BLOCKS) != prev_len:
        BALL.dir *= -1
    
    if PADDLE.rect.colliderect(BALL.rect):
        BALL.dir = 90 + (PADDLE.rect.centerx - BALL.rect.centerx) / PADDLE.rect.width * 80
    
    if BALL.rect.centerx < 0 or BALL.rect.centerx > 600:
        BALL.dir = 180 - BALL.dir
    if BALL.rect.centery < 0:
        BALL.dir = -BALL.dir
        BALL.speed = 15



pygame.init()
pygame.key.set_repeat(5, 5)
SURFACE = pygame.display.set_mode((600, 800))
FPSCLOCK = pygame.time.Clock()
BLOCKS = []
PADDLE = Block((242, 242, 0), Rect(300, 700, 100, 30))
BALL = Block((242, 242, 0), Rect(300, 400, 20, 20), 10)

def main():
    myfont = pygame.font.SysFont(None, 80)
    msg_clear = myfont.render("Cleared!", True, (255, 255, 0))
    msg_over = myfont.render("Game over!", True, (255, 255, 0))
    fps = 30
    colors = [(255, 0, 0), (255, 165, 0), (242, 242, 0),
              (0, 128,0), (128, 0, 128), (0, 0, 255)]
    for y_pos, color in enumerate(colors, start = 0):
        for x_pos in  range(0, 5):
            BLOCKS.append(Block(color, Rect(x_pos * 100 + 60, y_pos * 50 + 40, 80, 30)))
    
    while True:
        tick()
        SURFACE.fill((0, 0, 0))
        BALL.draw()
        PADDLE.draw()
        for block in BLOCKS:
            block.draw()
        if len(BLOCKS) == 0:
            SURFACE.blit(msg_clear, (200, 400))
        if BALL.rect.centery > 800 and len(BLOCKS) > 0:
            SURFACE.blit(msg_over, (150, 400))
        
        pygame.display.update()
        FPSCLOCK.tick(fps)

if __name__ == "__main__":
    main()

 

 

 

 

import sys
import random
import pygame
from pygame.locals import QUIT, KEYDOWN, K_LEFT, K_RIGHT, K_UP, K_DOWN, Rect

pygame.init()
pygame.key.set_repeat(5, 5) # control how held keys are repeated
SURFACE = pygame.display.set_mode([600, 600])
FPSCLOCK = pygame.time.Clock()

class Snake:
    def __init__(self, pos):
        self.bodies = [pos]
    
    def move(self, key):
        x_pos, y_pos = self.bodies[0]

        if key == K_LEFT:
            x_pos -= 1
        elif key == K_RIGHT:
            x_pos += 1
        elif key == K_UP:
            y_pos -= 1
        elif key == K_DOWN:
            y_pos += 1
        head = (x_pos, y_pos)

        is_game_over = head in self.bodies or \
            head[0] < 0 or head[0] >= W or \
            head[1] < 0 or head[1] >= H

        self.bodies.insert(0, head)
        if head in FOODS:
            i = FOODS.index(head)
            del FOODS[i]
            add_food(self)
        else:
            self.bodies.pop()
        return is_game_over
    
    def draw(self):
        for body in self.bodies:
            pygame.draw.rect(SURFACE, (0, 255, 255),
                             Rect(body[0] * 30, body[1] * 30, 30, 30))

FOODS = []
(W, H) = (20, 20)

def add_food(snake):
    while True:
        pos = (random.randint(0, W-1), random.randint(0, H - 1))
        if pos in FOODS or pos in snake.bodies:
            continue
        FOODS.append(pos)
        break

def paint(snake, msg):
    SURFACE.fill((0, 0, 0))
    snake.draw()

    for food in FOODS:
        pygame.draw.ellipse(SURFACE, (0, 255, 0),
                            Rect(food[0] * 30, food[1] * 30, 30, 30))
    for index in range(20):
        pygame.draw.line(SURFACE, (64, 64, 64),
                         (index*30, 0), (index*30, 600))
        pygame.draw.line(SURFACE, (64, 64, 64),
                         (0, index*30), (600, index* 30))
    
    if msg != None:
        SURFACE.blit(msg, (150, 300))
    pygame.display.update()

def main():
    myfont = pygame.font.SysFont(None, 80)
    key = K_DOWN
    msg = None
    game_over = False
    snake = Snake((int(W/2), int(H/2)))
    for _ in range(10):
        add_food(snake)
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                key = event.key
        
        if game_over:
            msg = myfont.render("Game Over!", True, (255, 255, 0))
        else:
            game_over = snake.move(key)
        
        paint(snake, msg)
        FPSCLOCK.tick(10)

if __name__ == "__main__":
    main()

 

 

 

 

 

 

 

import sys
from math import floor
from random import randint
import pygame
from pygame.locals import QUIT, MOUSEBUTTONDOWN

WIDTH = 20
HEIGHT = 15
SIZE = 50
NUM_OF_BOMBS = 20
EMPTY = 0
BOMB = 1
OPENED = 2
OPENED_COUNT = 0
CHECKED = [
    [
        0 for _ in range(WIDTH)
    ]
    for _ in range(HEIGHT)
]

pygame.init()
SURFACE = pygame.display.set_mode(([WIDTH * SIZE, HEIGHT * SIZE]))
FPSCLOCK = pygame.time.Clock()

def num_of_bomb(field, x_pos, y_pos):
    cnt = 0
    for y_off in range(-1, 2):
        for x_off in range(-1, 2):
            xpos, ypos = (x_pos + x_off, y_pos + y_off)
            if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and\
                field[ypos][xpos] == BOMB:
                cnt +=1
    return cnt

def open_tile(field, x_pos, y_pos):
    global OPENED_COUNT
    if CHECKED[y_pos][x_pos]:
        return
    CHECKED[y_pos][x_pos] = True

    for y_off in range(-1, 2):
        for x_off in range(-1, 2):
            xpos, ypos = (x_pos + x_off, y_pos + y_off)
            if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and\
                field[ypos][xpos] == EMPTY:
                field[ypos][xpos] = OPENED
                OPENED_COUNT += 1
                cnt = num_of_bomb(field, xpos, ypos)
                if cnt == 0 and not (xpos == x_pos and ypos == y_pos):
                    open_tile(field, xpos, ypos)

def main():
    small_font = pygame.font.SysFont(None, 36)
    large_font = pygame.font.SysFont(None, 72)
    msg_clear = large_font.render("!!CLEARED!!", True, (0, 255, 255))
    msg_over = large_font.render("GAME OVER!!", True, (0, 255, 255))
    msg_rect = msg_clear.get_rect()
    msg_rect.center = (WIDTH*SIZE/2, HEIGHT*SIZE/2)
    game_over = False

    field = [
        [
            EMPTY for x_pos in range(WIDTH)
        ]
        for y_pos in range(HEIGHT)
        ]
    cnt = 0
    while cnt < NUM_OF_BOMBS:
        x_pos, y_pos = randint(0, WIDTH-1), randint(0, HEIGHT - 1)
        if field[y_pos][x_pos] == EMPTY:
            field[y_pos][x_pos] = BOMB
            cnt +=1
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN and event.button == 1:
                x_pos, y_pos = floor(event.pos[0] / SIZE),\
                            floor(event.pos[1] / SIZE)
                if field[y_pos][x_pos] == BOMB:
                    game_over = True
                else:
                    open_tile(field, x_pos, y_pos)
        

        SURFACE.fill((0, 0, 0))
        for y_pos in range(HEIGHT):
            for x_pos in range(WIDTH):
                tile = field[y_pos][x_pos]
                rect = (x_pos * SIZE, y_pos * SIZE, SIZE, SIZE)
                if tile == EMPTY or tile == BOMB:
                    pygame.draw.rect(SURFACE, (192, 192, 192), rect)
                    if game_over and tile == BOMB:
                        pygame.draw.ellipse(SURFACE, (225, 225, 0), rect)
                elif tile == OPENED:
                    cnt = num_of_bomb(field, x_pos, y_pos)
                    if cnt > 0:
                        num_img = small_font.render(
                            "{}".format(cnt), True, (255, 255, 0)
                        )
                        SURFACE.blit(num_img, (x_pos * SIZE + 10, y_pos * SIZE + 10))

        for idx in range(0, WIDTH*SIZE, SIZE):
            pygame.draw.line(SURFACE, (96, 96, 96), (idx, 0), (idx, HEIGHT * SIZE))
        for idx in range(0, HEIGHT*SIZE, SIZE):
            pygame.draw.line(SURFACE, (96, 96, 96), (0, idx), (WIDTH*SIZE, idx))
        
        if OPENED_COUNT == WIDTH*HEIGHT - NUM_OF_BOMBS:
            SURFACE.blit(msg_clear, msg_rect.topleft)
        elif game_over:
            SURFACE.blit(msg_over, msg_rect.topleft)
        
        pygame.display.update()
        FPSCLOCK.tick(15)
    
if __name__ == "__main__":
    main()

계속 손에 안잡히고 시작 못해서

간단하게 파이게임 진행해보려고함.

 

 

 

 

파이게임 단순 화면띄우기 예제

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
pygame.display.set_caption("just window")

def main():
    while True:
        SURFACE.fill((255, 255, 255))

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

if __name__ == "__main__":
    main()

 

 

이벤트

- 이벤트 큐에 저장

- 큐 맨앞에 이벤트 꺼내 처리

 

 

 

간단한 글자 띄우기

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))

def main():
    sysfont = pygame.font.SysFont(None, 36)
    counter = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        counter += 1
        SURFACE.fill((0, 0, 0))
        count_image = sysfont.render("count is {}".format(counter), True, (255, 255, 255))
        SURFACE.blit(count_image, (50, 50))
        pygame.display.update()

if __name__ == "__main__":
    main()

 

 

fps 설정 1

- pygame.time.Clock() tick(10) 1초에 10번 루프

 

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()


def main():
    sysfont = pygame.font.SysFont(None, 36)
    counter = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        counter += 1
        SURFACE.fill((0, 0, 0))
        count_image = sysfont.render("count is {}".format(counter), True, (255, 255, 255))
        SURFACE.blit(count_image, (50, 50))
        pygame.display.update()

        FPSCLOCK.tick(10)

if __name__ == "__main__":
    main()

 

 

 

상자 그리기

 

import sys
import pygame
from pygame.locals import QUIT, Rect

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()


def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit
        SURFACE.fill((255, 255, 255))

        pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50))
        pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 30), 3)
        pygame.draw.rect(SURFACE, (0, 255, 0), ((100, 80), (80, 50)))

        rect0 = Rect((200, 60), (140, 80))
        pygame.draw.rect(SURFACE, (0, 0, 255), rect0)
        rect1 = Rect((30, 160), (100, 50))
        pygame.draw.rect(SURFACE, (255, 255, 0), rect1)

        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

 

import sys
import pygame
from pygame.locals import QUIT, Rect, Circle

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()


def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit
        SURFACE.fill((255, 255, 255))

        pygame.draw.circle(SURFACE, (255, 0, 0), (50, 50), 20)
        pygame.draw.circle(SURFACE, (255, 0, 0), (150, 50), 20, 10)


        pygame.draw.circle(SURFACE, (0, 255, 0), (50, 150), 10)
        pygame.draw.circle(SURFACE, (0, 255, 0), (150, 150), 20)
        pygame.draw.circle(SURFACE, (0, 255, 0), (250, 150), 30)

        pygame.draw.ellipse(SURFACE, (255, 0, 0), (50, 50, 140, 60))
        pygame.draw.ellipse(SURFACE, (255, 0, 0), (250, 30, 90, 90))

        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

 

 

원, 타원 그리기

import sys
import pygame
from pygame.locals import QUIT, Rect

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()


def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit
        SURFACE.fill((255, 255, 255))

        pygame.draw.circle(SURFACE, (255, 0, 0), (50, 50), 20)
        pygame.draw.circle(SURFACE, (255, 0, 0), (150, 50), 20, 10)


        pygame.draw.circle(SURFACE, (0, 255, 0), (50, 150), 10)
        pygame.draw.circle(SURFACE, (0, 255, 0), (150, 150), 20)
        pygame.draw.circle(SURFACE, (0, 255, 0), (250, 150), 30)

        pygame.draw.ellipse(SURFACE, (255, 0, 0), (50, 50, 140, 60))
        pygame.draw.ellipse(SURFACE, (255, 0, 0), (250, 30, 90, 90))

        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

선긋기

 

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 220))
FPSCLOCK = pygame.time.Clock()

def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        
        SURFACE.fill((255, 255, 255))
        pygame.draw.line(SURFACE, (255, 0, 0), (10, 80), (200, 80))
        pygame.draw.line(SURFACE, (255, 0, 0), (10, 150), (200, 150), 15)
        pygame.draw.line(SURFACE, (0, 255, 0), (250, 30), (250, 200))

        start_pos = (300, 30)
        end_pos = (380, 200)
        pygame.draw.line(SURFACE, (0, 0, 255), start_pos, end_pos, 10)

        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

 

 

 

그리드 만들기

 

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        SURFACE.fill((0, 0, 0))

        for xpos in range(0, 400, 25):
            pygame.draw.line(SURFACE, 0xFFFFFF, (xpos, 0), (xpos,300))
        for ypos in range(0, 300, 25):
            pygame.draw.line(SURFACE, 0xFFFFFF, (0, ypos), (400, ypos))
        pygame.display.update()
        FPSCLOCK.tick(3)
    

if __name__ == "__main__":
    main()

 

 

 

 

 

 

이은선

 

import sys
import random
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        SURFACE.fill((0, 0, 0))

        pointlist = []
        for _ in range(10):
            xpos = random.randint(0, 400)
            ypos = random.randint(0, 300)
            pointlist.append((xpos, ypos))
        
        pygame.draw.lines(SURFACE, (255, 255, 255), True, pointlist, 5)
        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

 

 

텍스트 쓰기

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 200))
FPSCLOCK = pygame.time.Clock()

def main():
    sysfont = pygame.font.SysFont(None, 72)
    msg = sysfont.render("hello python", True, (0, 128, 128))
    msg_rect = msg.get_rect()
    msg_rect.center = (200, 100)


    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        SURFACE.fill((255, 255, 255))
        SURFACE.blit(msg, msg_rect)
        pygame.display.update()
        FPSCLOCK.tick(3)

if __name__ == "__main__":
    main()

 

 

 

 

 

 

텍스트 줌 회전

import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 200))
FPSCLOCK = pygame.time.Clock()

def main():
    sysfont = pygame.font.SysFont(None, 72)
    msg = sysfont.render("hello python", True, (0, 128, 128))
    msg_rect = msg.get_rect()
    theta = 0
    scale = 1


    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        SURFACE.fill((255, 255, 255))

        theta += 5
        scale = (theta % 360) / 180
        tmp_msg = pygame.transform.rotozoom(msg, theta, scale)
        tmp_rect = tmp_msg.get_rect()
        tmp_rect.center = (200,150)


        SURFACE.blit(tmp_msg, tmp_rect)
        pygame.display.update()
        FPSCLOCK.tick(30)

if __name__ == "__main__":
    main()

 

 

 

마우스 클릭 이벤트

import sys
import pygame
from pygame.locals import QUIT, MOUSEBUTTONDOWN

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
    mousepos = []
    while True:
        SURFACE.fill((255, 255, 255))
        
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN:
                mousepos.append(event.pos)
        
        for pos in mousepos:
            pygame.draw.circle(SURFACE, (0, 255, 0), pos, 5)
        
        pygame.display.update()
        FPSCLOCK.tick(10)

if __name__ == "__main__":
    main()

 

+ Recent posts