밑에첨부한 music는 배경음입니다. 코드 import pygame #라이브러리로딩 pygame.mixer.init(44100, -16,2,2048)#초기화 pygame.mixer.music.load('music.mp3')#음악로딩 pygame.mixer.music.play(-1)#-1로지정하면무한반복 import sys #종료하기위함 import time #게임이므로시간이있어야됨 import random #랜덤으로위치하기위함 from pygame.locals import *#시작 WINDOW_WIDTH = 760 #창크기설정 WINDOW_HEIGTH = 760 #창크기설정 GRID_SIZE = 20 #뱀의크기를지정 GRID_WIDTH = WINDOW_WIDTH / GRID_SIZE #뱀의크기를지정 GRID_HEIGTH = WINDOW_HEIGTH / GRID_SIZE #뱀의크기를지정 BLACK = (0, 0, 0) #검은색지정 WHITE = (255, 255, 255) #흰색지정 GRAY = (130, 130, 130) #회색지정
UP = (0, -1) #위로이동할수있게함(좌표로보면됨) DOWN = (0, 1) #아래로이동할수있게함 LEFT = (-1, 0) #왼쪽으로이동할수있게함 RIGHT = (1, 0) #오른쪽으로이동할수있게함 FPS = 20 #FPS지정 class Snake(object): #뱀을생성 def __init__(self): self.create() #뱀을생성 self.color = WHITE#뱀색깔 흰색 지정 def create(self): self.length = 3 #게임시작초기뱀길이 3지정 self.positions = [((WINDOW_WIDTH / 2), (WINDOW_HEIGTH / 2))] #뱀정가운데위치 self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) #뱀머리부분생성될때랜덤으로생성 def control(self, xy): #뱀조종 if (xy[0] * -1, xy[1] * -1) == self.direction: #반대방향조작금지시키기 return else: #그외에는허용 self.direction = xy def move(self): cur = self.positions[0]#좌표지정 x, y = self.direction nx = cur[0] + (x * GRID_SIZE)#벽좌표지정 ny = cur[1] + (y * GRID_SIZE) new = (nx, ny) if 0 > nx or nx > WINDOW_WIDTH:#뱀이벽에부딪히면죽음 self.create() elif 0 > ny or ny > WINDOW_HEIGTH:#뱀이벽에부딪히면죽음 self.create() elif new in self.positions[2:]:#뱀이벽에부딪히면죽음 self.create() else: self.positions.insert(0, new) if len(self.positions) > self.length:#자기몸을관통하면죽음 self.positions.pop() def eat(self): self.length += 1 #뱀이먹이를먹으면 길이 1증가 def draw(self, surface): for p in self.positions:#뱀그림그리기 draw_object(surface, self.color, p)#색깔표현
class Feed(object):#먹이생성 def __init__(self): #초기화시켜줌 self.position = (0, 0)#위치정해줌 self.color = GRAY#먹이색깔회색으로설정 self.create()#먹이생성 def create(self): self.position = (random.randint(0, GRID_WIDTH - 1) * GRID_SIZE, random.randint(0, GRID_HEIGTH - 1) * GRID_SIZE) #게임화면의먹이랜덤생성 def draw(self, surface):#먹이그려줌 draw_object(surface, self.color, self.position)#먹이호출 def draw_object(surface, color, pos):#뱀만아니라사과를그리기위해함수설정 r = pygame.Rect((pos[0], pos[1]), (GRID_SIZE, GRID_SIZE))#사각형모양설정 pygame.draw.rect(surface, color, r)#사각형모양설정 def check_eat(snake, feed): #뱀이먹이를먹었을때확인 if snake.positions[0] == feed.position:#머리부분이먹이에위치해있으면 snake.eat()#뱀이먹는다 feed.create()#먹이다시생성 def show_info(length, speed, surface):#보여줄정보 설정 font = pygame.font.Font(None, 30)#폰트와글씨체설 text = font.render("SCORE: " + str(length * 100) + " SPEED: " + str(round(speed, 2)), 1, GRAY)#텍스트에표시될내용과 색깔정하기 pos = text.get_rect() #텍스트위치지정 pos.centerx = 150 surface.blit(text, pos)
if __name__== '__main__': #메인함수역할 snake = Snake()#뱀이라는객체생성 feed = Feed()#먹이라는객체생 pygame.init()#파이게임초기화 그래야게임실행가능 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGTH), 0, 32)#파이게임을돌릴창 pygame.display.set_caption('Snake game') surface = pygame.Surface(window.get_size())#창사이즈 써페이스에넣어줌 surface = surface.convert() #공간을 전환시키는용도 surface.fill(BLACK) #공간을 검은색으로 채움 clock = pygame.time.Clock() #게임의 시간생성 pygame.key.set_repeat(1, 40) window.blit(surface, (0, 0)) #화면구성 while True: for event in pygame.event.get():#키보드조작전에끝내는걸로끄면게임종료 if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN:#뱀조종하기위해넣어놓음 if event.key == K_UP: snake.control(UP)#뱀조종하기위해넣어놓음 elif event.key == K_DOWN: snake.control(DOWN)#뱀조종하기위해넣어놓음 elif event.key == K_LEFT: snake.control(LEFT)#뱀조종하기위해넣어놓음 elif event.key == K_RIGHT: snake.control(RIGHT)#뱀조종하기위해넣어놓음 surface.fill(BLACK) #화면검은색으로 생성 snake.move()#뱀이움직임 check_eat(snake, feed)#먹이먹었는지확인 speed = (snake.length + FPS) / 2 #뱀길이와 FPS를합친값을 나눈값만큼속도증가 show_info(snake.length, speed, surface)#정보표시 snake.draw(surface)#뱀그림 feed.draw(surface)#먹이그림 window.blit(surface, (0, 0)) pygame.display.flip()#디스플레이플립 pygame.display.update()#업데이트 clock.tick(speed) #틱단위로컴퓨터가작동하므로 속도를틱지정
|