enemy들은 우측에서 무작위로 나오게 되어 있다. 이것들을 피하거나 제거해야 하는데 기능을 따로 주지 않았기 때문에 피할수는 없고 무기를 쐬서 제거를 해줘야 한다. 캐릭터도 스틱으로 움직히게 하면 되지만 예제는 예제니깐 간단히 하자.
-----------game.py--------------
import pygame
import random
import os
WIDTH = 800
HEIGHT = 480
FPS = 30
# Define colors
player1Color = (0, 180, 255)
player2Color = (180, 0, 180)
BGCOLOR = (255, 200, 0) #background color
WHITE = (255,255,255)
enemyColor = (0, 5, 255)
# set up assets folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
# Player Class
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join(img_folder, "player1_1.png")).convert() # 이미지를 사용하는 경우
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH/2 - 100, HEIGHT - 50)
self.y_speed = 3
def update(self):
self.rect.x += 3
self.rect.y += self.y_speed
if self.rect.bottom > HEIGHT:
self.rect.y = 0
if self.rect.top < 50:
self.y_speed = 3
if self.rect.left > WIDTH:
self.rect.right = 0
# 외곽를 지나면 처리
if self.rect.left > WIDTH:
self.rect.right = 0
if self.rect.right < 0:
self.rect.left = WIDTH
def shoot(self):
bullet = Bullet(player1.rect.x+25, player1.rect.y+25)
bullet_sprites.add(bullet)
all_sprites.add(bullet)
# Class
class Box(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((60, 20)) # 도형을 사용하는 경우
self.image.fill(player2Color)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH/2, HEIGHT - 45)
self.x_speed = 0
def update(self):
self.rect.x += self.x_speed
# 스틱을 움직이면
if event.type == pygame.JOYAXISMOTION:
self.x_speed += gamepads[-1].get_axis(0) *1
if self.x_speed > 10:
self.x_speed = 10
# self.rect.y += gamepads[-1].get_axis(1) *4
if self.rect.left > WIDTH:
self.rect.right = 0
if self.rect.right < 0:
self.rect.left = WIDTH
# Enemy Class
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 30)) # 도형을 사용하는 경우
self.image.fill(enemyColor)
self.rect = self.image.get_rect()
self.rect.center = (random.randrange(WIDTH, WIDTH *2), random.randrange(50, HEIGHT - 50))
self.x_speed = random.randrange(-5, -1)
def update(self):
self.rect.x += self.x_speed
if (self.rect.right < 0):
self.rect.left = WIDTH
self.rect.top = random.randrange(100, 300)
# bullets
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10, 3)) # 도형을 사용하는 경우
self.image.fill(player2Color)
self.rect = self.image.get_rect()
self.rect.center = (x,y)
self.x_speed = 20
def update(self):
self.rect.x += self.x_speed
if self.rect.left > WIDTH:
self.kill() # 오호 이거 편하네 .
# initialize
pygame.init()
pygame.mixer.init() #for sound
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Jumper')
clock = pygame.time.Clock()
width, height = pygame.display.get_surface().get_size()
lead_x = width/2 -100
lead_y = height - 100
lead2_x = width/2 + 100
lead2_y = height - 100
#연결된 모든 디바이스 배열에 추가
gamepads = []
for i in range(0, pygame.joystick.get_count()):
gamepads.append(pygame.joystick.Joystick(i))
gamepads[-1].init()
# set up sprites
all_sprites = pygame.sprite.Group()
player_sprites = pygame.sprite.Group()
bullet_sprites = pygame.sprite.Group()
enemy_sprites = pygame.sprite.Group()
player1 = Player()
player_sprites.add(player1)
box_sprites = pygame.sprite.Group()
box = Box()
box_sprites.add(box)
# for문
for i in range(10):
enemy = Enemy()
enemy_sprites.add(enemy)
all_sprites.add(enemy)
all_sprites.add(player1)
all_sprites.add(box)
# print(all_sprites)
#Game Loop
running = True
while running:
clock.tick(FPS)
# process input(events)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 버튼을 누르면
if event.type == pygame.JOYBUTTONDOWN :
if event.button == 0:
player1.shoot()
# update
all_sprites.update()
hits = pygame.sprite.groupcollide(enemy_sprites, bullet_sprites, True, True)
if hits:
# 새로운 enemy를 추가해 줌
enemy = Enemy()
enemy_sprites.add(enemy)
all_sprites.add(enemy)
# 충돌감지
hit = pygame.sprite.spritecollide(player1, box_sprites, False)
if hit:
player1.y_speed *= -1
# draw / render
screen.fill(BGCOLOR)
all_sprites.draw(screen)
pygame.display.update() # or flip()
pygame.quit()
quit()
-----------------
각각의 요소들은 클래스를 이용해서 생성하고 sprite 그룹에 등록해서 관리를 편하게 해준다. 충돌 감지등을 할때 편리하다. 각각의 스프라이트 클래스에 원하는대로 동작이나 모양을 지정해 주면 된다.