2017년 1월 10일 화요일

CCNA 4일차

허브와 스위치의 Broadcast / Collision Domain

- 허브는 collision domain이 하나라 이론상 500대, 실제로 200대정도밖에 연결하지 못함.
- 스위치는 port별로 collision domain이 나눠짐.
- 허브는 collision domain을 나누지 못함.
- 스위치와 스위치 사이에도 collision domain이 나눠짐.

- Broadcast domain 과 collision domain 개수세기

3. 브릿지(Bridge)
- 하나의 브로드캐스트 도메인을 둘 또는 셋의 컬리전 도메인으로 나눠주는 장치
- 현재는 스위치에 밀려 거의 사용되고 있지 않다.

4. 스위치 & 브릿지의 기능
1) Learning
- MAC 주소를 배움
- Source MAC 주소만 배움! (받는 쪽이 불분명할 수도 있다.)
- Destination MAC은 배우지 않음.

2) Flooding
- MAC주소를 모르면 브로드캐스트

3) Forwarding
- MAC 주소를 알면 유니캐스트(해당 호스트에게만 전달)

4) Filtering
- 3)의 포워딩이 일어나면 나머지 포트로 필터링
- 1)에서 수집한 MAC을 기준으로 통신을 차단할 수 있다.

5) Aging
- 1) 에서 배운 MAC주소에 대한 유효수명 부여
- 기본값은 300초
- 통신이 지속되면 300초로 갱신

5. 스위치와 브릿지의 차이점
1) 처리 방식
- 브릿지는 소프트웨어 방식으로 기능, 스위치는 하드웨어 방식으로 동작.
- 하드웨어 방식으로 동작하는 것을 ASIC(Application Specific Integrated Circuit)이라고 한다.
- 스위치는 하드웨어 방식이기 때문에 훨씬 빠르다.

2) 브릿지는 모든 포트의 속도가 같아야 하지만 스위치는 포트별로 속도가 달라도 동작한다.

3) 스위치는 브릿지에 비해 훨씬 많은 포트를 제공

4) 스위치는 Cut-through와 store and forward 방식으로 동작하지만 브릿지는 store and forward 방식으로만 동작.
일부 스위치는 추가로 fragment free 방식도 지원
- cut through : 실시간으로 들어오는 패킷의 주소를 확인 후 포워딩이나 플루딩으로 패킷을 처리하는 방법
- store and forward : 패킷을 일단 저장한 후 패킷의 주소를 확인 후 처리
- fragment free : 실시간으로 들어오는 패킷을 확인할 때 주소를 포함한 512비트를 확인하고 처리. 보안장비 등에서 사용. (96비트의 보내는 MAC, 받는 MAC 뿐만이 아니라 헤더를 검사)

6. 루핑(Looping)
- 패킷이 네트워크상에서 무한 반복되는 현상
- 루핑을 막기 위해 Spanning Tree Protocol에 의해서 스위치들은 단일 경로만을 구성한다.

2017년 1월 9일 월요일

CCNA 3일차

OSI 7 계층


LAN의 종류

1. Ethernet
- 제록스와 인텔이 개발
- CSMA/CD 방식
- Carrier Sense Multiple Access / Collision Detection
- 신호 검출 다중 접근 / 충돌 감지
- 일정 횟수만큼 ack가 올때까지 계속 재전송.(15회)
- 15회 실패할 경우 상위 계층에 알리고 종료.
- 많은 수가 연결되면 충돌확률이 늘어난다.
- 10Mbps
- Fast Ethernet(100Mbps), Gigabit Ethernet(1000Mbps - 1Gbps)
https://ko.wikipedia.org/wiki/%EC%9D%B4%EB%8D%94%EB%84%B7

2. 토큰 버스/링
- IBM이 개발
- 4Mbps, 16Mbps

- Backbone을 이용한 버스 방식
- 한번에 토큰을 가지고 있는 하나만 통신 가능.
- 문제를 파악하기가 쉽다.
- 버스가 가지고 있는 시간적 문제를 해결하기 위해 링 형태가 나옴.
- 규모가 커지면 속도가 느려지거나 응답시간이 길어짐.

3. 기타 등등
- Appletalk, FDDI 등등


TTL
- Time To Live
- TTL 안에 패킷이 목적지에 도달하지 못하면 패킷은 소멸된다.

왕복 시간은 100ms 이하.
손실률 2% 미만.

wireshark 이용해서 패킷 관찰

ethernet II
protocol
message


1. 허브(HUB)
- Ethernet 의 중심이 되는 장치
- Port : 데이터를 서로간에 교환할 수 있는 곳
- 여러개의 Port에 Host들을 연결하고 브로드캐스트 해주는 장치
- 단순히 신호 전달만을 하기 때문에 멀티포트 리피터(Multiport Repeater)라고도 한다.
- 단순히 신호전달만을 하기 때문에 OSI 7 Layer 중 L1에 해당

1)단점
- 호스트가 많아지면 충돌이 발생할 확률이 높아진다.
- 충돌이 발생하면 15회까지 재전송

2. 스위치(Switch)
- 허브의 역할을 한다고 해서 스위칭 허브라고도 표현
- 하나의 브로드캐스트 도메인을 여러개의 Collision 도메인으로 나눠주는 역할
- 브로드캐스트 도메인 : LAN(한번에 브로드캐스트 할 수 있는 영역)
- 포워딩
- MAC 주소를 기반으로 동작하기 때문에 L2 장비로 분류
- MAC 주소를 기반으로 하나의 브로드캐스트 도메인을 여러개의 컬리전 도메인으로 분류
- 유니캐스트 통신인 경우 허브와는 달리 하나의 회선에서 충돌이 발생해도
- 나머지 회선의 호스트들에게 영향을 미치지 않고 통신이 가능하다.

CCNA 2일차

네트워크에서 통신방식

- 노드(호스트)들을 구분하기 위한 식별자(Identifier)가 기본적으로 필요하다.
- 각각의 개체를 고유하게 식별할 수 있게 해주는 식별자를 MAC(Media Access Control) Address라고 한다.
- 같은 LAN 안에서의 통신은 MAC을 기반으로 이루어진다.

- 물리적 주소 앞 6자리(제조업체), 뒤 6자리(일련번호)
cmd - ipconfig /all 명령어를 통해 MAC주소를 확인할 수 있다.

1. 브로드캐스트
- Broad + Cast
- 수신 대상을 정하지 않고 모두에게 전달하는 통신방식
- 브로드캐스트가 전달되는 범위를 LAN 으로 정의한다.

- 방송과 같이 신호를 뿌리면 받는 사람이 송신한다.
- 듣는 대상이 고려되어 있지 않다.
- 한번에 신호를 보낼 수 있는 범위가 정해져 있으며
- 그 범위는 LAN 이다. (근거리)

- 반면 멀티캐스트나 유니캐스트는 LAN을 넘어서도 통신가능

2. 멀티캐스트
- Multi + Cast
- 하나의 그룹(다수의 수신자)에게 신호를 전달하는 통신 방식

- 멀티캐스트를 전체에게 전달하지 않는 것은 아니다.
- 신호를 받는 측에서 온 신호를 선별한다.

3. 유니캐스트
- Uni + Cast (단일)
- 하나의 대상에게만 신호를 전달하는 통신 방식

4. 애니캐스트
- Ani + Cast



MAC(Media Access Control) Address 을 알아보자

1. MAC Address란?
2진수 48비트로 이루어진 숫자체계
16진수 1자리는 4비트
16진수 12자리로 표시할 수 있다
D0-50-99-8B-4D-96
D0:50:99:8B:4D:96
D050.998B.4D96


앞의 24비트(3바이트, 16진수 6자리)는 제조사(벤더)를 의미하고
(OUI:Oraganizaion Unique Identifier)
뒤의 24비트는 제조사가 사용하는 일련번호를 의미

https://regauth.standards.ieee.org/standards-ra-web/pub/view.html#registries
위 사이트를 통해 제조사를 확인할 수 있다.


유니캐스트
보내는쪽
00-60-80-AA-BB-CC
받는쪽
00-60-80-DD-EE-FF

브로드캐스트
보내는쪽
00-60-80-AA-BB-CC
받는쪽
FF-FF-FF-FF-FF-FF

- ip에서도 동일

2. 그럼 MAC을 어떻게 알아내서 통신을 하는 것일까?
- ARP(Address Resolution Protocol) 와 RARP(Reverse ARP)

- PC1이 PC2와 통신을 하려고 할 때
- PC1은 자신의 MAC 주소는 알고 있으나, PC2의 MAC 주소를 알지 못한다.
- 그래서 PC1이 PC2의 MAC 주소를 알아내기 위해서 네트워크에 자신의 MAC주소를 적은 PC2를 찾는 메시지를 브로드캐스트하게 된다.
- PC2는 브로드캐스트를 듣고 PC1에게 응답하기 위해서 자신의 MAC주소를 적어서 브로드캐스트로 응답한다.
- PC1이 PC2의 주소가 적힌 브로드캐스트를 듣고 PC2의 MAC을 확인하고 난 뒤 자신의 MAC Address Table에 메모한다.
- 이후 PC1은 PC2에게 유니캐스트로 통신을 할 수 있다.
- 이렇게 MAC 주소를 알아내는 과정을 ARP라고 한다. (IP주소를 가지고 MAC주소를 알아내는 과정)
- 역으로 MAC 주소를 가지고 IP주소를 알아내는 과정을 RARP라고 한다.
- MAC 주소를 위변조 하는 네트워크 해킹 기법을 spoofing이라고 한다.

cmd > arp -a
PC에 저장된 MAC Address Table을 보여준다.

CCNA 1일차

네트워크
- 일을 할 수 있는 망 또는 관계

네트워크를 사용하는 이유는?
- 공유(share)하기 위해서

무엇을 공유?
1. 자원(Resource)
2. 정보(Information)


네트워크의 종류

1. 인터넷
- Inter + Net (상호간의)
- 네트워크를 여러개 묶어 놓은 것
예> 인터넷, 인터폰, 인터폴, 인터 컨티넨털, 인터내셔널

2. 인트라넷
- Intra + Net (내부)
- 인터넷 기술을 사용해서 회사 내부에 내부직원만 이용하는 서비스를 구축한 것

3. 엑스트라넷
- Extra + Net (확장)
- 인트라넷을 인터넷을 사용해서 외부 직원이나 고객이 이용할 수 있도록 확장한 것



네트워크의 종류 - 범위에 따른 분류

1. LAN
- Local Area Network
- 근거리 통신망
- 라우터를 거치지 않고 직접 통신할 수 있는 네트워크

2. NAN
- Netropolitian Area Network
- 광역도시권 통신망

3. WAN
- Wide Area Network
- 원거리 통신망
- 라우터를 사용해서 연결된 네트워크 모음. 국가단위나 전세계적인 규모를 의미.


cf) 네트워크에서 말하는 거리는 물리적인 거리가 아니다.
네트워크에서의 거리는 홉카운트(Hop Count)를 의미한다.

cmd - tracert (url)
호스트로부터 적은 도메인까지의 홉카운트들의 ip를 보여준다.
보안상의 이유로 * 으로 표시되는 서버들도 있다.

2016년 5월 14일 토요일

Pygame 틱택토 게임 (Tic-Tac-Toe) (2)

import random, pygame, sys
from pygame.locals import *
FPS = 30 # frames per second, the general speed of the program
WINDOWWIDTH = 340 # size of window's width in pixels
WINDOWHEIGHT = 340 # size of windows' height in pixels
BOXSIZE = 100 # size of box height & width in pixels
GAPSIZE = 10 # size of gap between boxes in pixels
BOARDWIDTH = 3 # number of columns of icons
BOARDHEIGHT = 3 # number of rows of icons
# Colorset
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (100, 100, 100)
LIGHTBLUE = (153, 204, 255)
BGCOLOR = WHITE
BOXCOLOR = BLACK
HIGHLIGHTCOLOR = GRAY
LINECOLOR = WHITE
def main():
global FPSCLOCK, DISPLAYSURF
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
pygame.display.set_caption('TicTacToe - harang97')
mainBoard = [[None,None,None],[None,None,None],[None,None,None]]
playerTurn = 'X'
firstSelection = None # stores the (x, y) of the first box clicked.
DISPLAYSURF.fill(BGCOLOR)
drawBoard(mainBoard)
Message = 'None'
while True: # main game loop
mouseClicked = False
DISPLAYSURF.fill(BGCOLOR)
drawBoard(mainBoard)
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouseClicked = True
boxx, boxy = getBoxAtPixel(mousex, mousey)
if boxx != None and boxy != None:
# the mouse is currently over a box.
if mainBoard[boxx][boxy] == None:
drawHighlightBox(boxx, boxy)
if mainBoard[boxx][boxy] == None and mouseClicked:
mainBoard[boxx][boxy] = playerTurn # set the box as "filled"
drawXO(playerTurn, boxx, boxy)
if playerTurn == 'X':
playerTurn = 'O'
else: playerTurn = 'X'
# Algorithm that check the game is over
if hasWon(mainBoard):
if playerTurn == 'X': Message = 'Player 1 Wins!'
else: Message = 'Player 2 Wins!'
popMessage(Message)
mainBoard = [[None,None,None],[None,None,None],[None,None,None]]
playerTurn = 'X'
elif hasDraw(mainBoard):
Message = '   Draw!    '
popMessage(Message)
mainBoard = [[None,None,None],[None,None,None],[None,None,None]]
playerTurn = 'X'
# Redraw the screen and wait a clock tick.
pygame.display.update()
FPSCLOCK.tick(FPS)
def popMessage(Message):
font = pygame.font.Font('font/nanum.ttf', 32)
textSurface = font.render(Message, True, BLACK, LIGHTBLUE)
textRect = textSurface.get_rect()
textRect.center = (170, 85)
DISPLAYSURF.blit(textSurface, textRect)
pygame.display.update()
pygame.time.wait(2000)
def getBoxAtPixel(x, y):
# Draw Box on display surface
for boxx in range(BOARDWIDTH):
for boxy in range(BOARDHEIGHT):
left, top = leftTopCoordsOfBox(boxx, boxy)
boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
if boxRect.collidepoint(x, y):
return (boxx, boxy)
return (None, None)
def drawBoard(board):
# Draws all of the boxes in their covered or revealed state.
for boxx in range(BOARDWIDTH):
for boxy in range(BOARDHEIGHT):
left, top = leftTopCoordsOfBox(boxx, boxy)
if board[boxx][boxy] == None:
pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
else:
pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
drawXO(board[boxx][boxy], boxx, boxy)
def leftTopCoordsOfBox(boxx, boxy):
# Convert board coordinates to pixel coordinates
left = boxx* (BOXSIZE + GAPSIZE) + GAPSIZE
top = boxy * (BOXSIZE + GAPSIZE)  + GAPSIZE
return (left, top)
def drawHighlightBox(boxx, boxy):
left, top = leftTopCoordsOfBox(boxx, boxy)
pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left , top , BOXSIZE , BOXSIZE))
def drawXO(playerTurn, boxx, boxy):
left, top = leftTopCoordsOfBox(boxx, boxy)
if playerTurn == 'X':
pygame.draw.line(DISPLAYSURF, LINECOLOR, (left + 3, top + 3), (left + BOXSIZE - 3, top + BOXSIZE - 3), 4)
pygame.draw.line(DISPLAYSURF, LINECOLOR, (left + BOXSIZE - 3, top + 3), (left + 3, top + BOXSIZE - 3), 4)
else:
HALF = int(BOXSIZE / 2)
pygame.draw.circle(DISPLAYSURF, LINECOLOR, (left + HALF, top + HALF), HALF - 3, 4)
def hasWon(board):
# Returns True if player 1 or 2 wins
for xrow in board: # horizontal
if xrow[0] != None and xrow[0] == xrow[1] and xrow[1] == xrow[2]:
return True
for i in range(3): # vertical
if board[0][i] != None and board[0][i] == board[1][i] and board[1][i] == board[2][i]:
return True
if board[0][0] != None and board[0][0] == board[1][1] and board[1][1] == board[2][2]: # diagnol 1
return True
if board[2][0] != None and board[2][0] == board[1][1] and board[1][1] == board[0][2]: # diagnol 2
return True
return False # no winner
def hasDraw(board):
# Returns True if all the boxes have been filled
for i in board:
if None in i:
return False
return True
if __name__ == '__main__':
main()

(1)에서 구현해야 할 점 구현 완료!

부족한 점
- 승리시 표시하는 배경 박스를 그린 후 배경색이 없는 텍스트를 그리려 했으나, 결국 텍스트 배경색 이용
- 승리&무승부시 텍스트가 떠 있는 상태에서 클릭을 할 경우 다음 판에 반영된다.

보완점
- 텍스트를 사용하는 것이 아니라 팝업 텍스트 자체를 png로 저장한 후 불러오는 방법 고려

알게된 점
- pygame.display.update() 함수를 사용하는 이유는 화면 상에서 그래픽 변경 사항을 저장한 후 실제로 우리가 볼 수 있도록 하기 위해서이다.

Pygame 틱택토 게임 (Tic Tac Toe) 만들기 (1)


import random, pygame, sys
from pygame.locals import *

FPS = 30 # frames per second, the general speed of the program
WINDOWWIDTH = 340 # size of window's width in pixels
WINDOWHEIGHT = 340 # size of windows' height in pixels
BOXSIZE = 100 # size of box height & width in pixels
GAPSIZE = 10 # size of gap between boxes in pixels
BOARDWIDTH = 3 # number of columns of icons
BOARDHEIGHT = 3 # number of rows of icons

# Colorset
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (100, 100, 100)

BGCOLOR = WHITE
BOXCOLOR = BLACK
HIGHLIGHTCOLOR = GRAY
LINECOLOR = WHITE

O = 'O'
X = 'X'

def main():
 global FPSCLOCK, DISPLAYSURF
 pygame.init()
 FPSCLOCK = pygame.time.Clock()
 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

 mousex = 0 # used to store x coordinate of mouse event
 mousey = 0 # used to store y coordinate of mouse event
 pygame.display.set_caption('TicTacToe - harang97')

 mainBoard = [[None,None,None],[None,None,None],[None,None,None]]
 playerTurn = 'X'

 firstSelection = None # stores the (x, y) of the first box clicked.

 DISPLAYSURF.fill(BGCOLOR)
 drawBoard(mainBoard)

 while True: # main game loop
  mouseClicked = False

  DISPLAYSURF.fill(BGCOLOR)
  drawBoard(mainBoard)

  for event in pygame.event.get():
   if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
    pygame.quit()
    sys.exit()
   elif event.type == MOUSEMOTION:
    mousex, mousey = event.pos
   elif event.type == MOUSEBUTTONUP:
    mousex, mousey = event.pos
    mouseClicked = True

  boxx, boxy = getBoxAtPixel(mousex, mousey)
  if boxx != None and boxy != None:
   # the mouse is currently over a box.
   if mainBoard[boxx][boxy] == None:
    drawHighlightBox(boxx, boxy)
   if mainBoard[boxx][boxy] == None and mouseClicked:
    mainBoard[boxx][boxy] = playerTurn # set the box as "filled"
    drawXO(playerTurn, boxx, boxy)
    if playerTurn == 'X':
     playerTurn = 'O'
    else: playerTurn = 'X'

    # Algorithm that check the game is over
    if hasWon(mainBoard):
     pass
    if hasDraw(mainBoard):
     pass
    # -----------------------------
  # Redraw the screen and wait a clock tick.
  pygame.display.update()
  FPSCLOCK.tick(FPS)


def getBoxAtPixel(x, y):
 # Draw Box on display surface
 for boxx in range(BOARDWIDTH):
  for boxy in range(BOARDHEIGHT):
   left, top = leftTopCoordsOfBox(boxx, boxy)
   boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
   if boxRect.collidepoint(x, y):
    return (boxx, boxy)
 return (None, None)


def drawBoard(board):
 # Draws all of the boxes in their covered or revealed state.
 for boxx in range(BOARDWIDTH):
  for boxy in range(BOARDHEIGHT):
   left, top = leftTopCoordsOfBox(boxx, boxy)
   if board[boxx][boxy] == None:
    pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
   else:
    pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
    drawXO(board[boxx][boxy], boxx, boxy)


def leftTopCoordsOfBox(boxx, boxy):
 # Convert board coordinates to pixel coordinates
 left = boxx* (BOXSIZE + GAPSIZE) + GAPSIZE
 top = boxy * (BOXSIZE + GAPSIZE)  + GAPSIZE
 return (left, top)


def drawHighlightBox(boxx, boxy):
 left, top = leftTopCoordsOfBox(boxx, boxy)
 pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left , top , BOXSIZE , BOXSIZE))

def drawXO(playerTurn, boxx, boxy):
 left, top = leftTopCoordsOfBox(boxx, boxy)
 if playerTurn == 'X':
  pygame.draw.line(DISPLAYSURF, LINECOLOR, (left + 3, top + 3), (left + BOXSIZE - 3, top + BOXSIZE - 3), 4)
  pygame.draw.line(DISPLAYSURF, LINECOLOR, (left + BOXSIZE - 3, top + 3), (left + 3, top + BOXSIZE - 3), 4)
 else:
  HALF = int(BOXSIZE / 2)
  pygame.draw.circle(DISPLAYSURF, LINECOLOR, (left + HALF, top + HALF), HALF - 3, 4)

def hasWon(board):
 # Returns True if player 1 or 2 wins
 return True


def hasDraw(board):
 # Returns True if all the boxes have been filled
 for i in board:
  if None in i:
   return False
 return True

if __name__ == '__main__':
 main()

현재 완료
- 기본 그래픽 바탕
- 마우스 커서가 빈 공간에 올라올 경우 하이라이트
- 클릭시 차례에 따라 X 또는 O가 바탕에 남음

추가할 것
- 승리, 무승부 판별 함수 만들기
- 승리, 무승부시 누가 승리했는지 표시 후 초기화하기

2016년 5월 10일 화요일

Pygame (4) 폰트 불러오기, 화면에 글씨쓰기

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400,300))
pygame.display.set_caption('Hello World!')

WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 128)
BLACK = (0, 0, 0)

fontObj = pygame.font.Font('font/nanum.ttf', 32)
textSurfaceObj = fontObj.render('Hello world!', True, BLACK, WHITE)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (100, 16)

while True: # main game loop
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(textSurfaceObj, textRectObj)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()


---------

Anti-Aliasing == False

Anti-Aliasing == True



fontObj란 변수에 pygame.font.Font를 이용해 .ttf 형식 등의 폰트 파일을 불러와 저장합니다.
미리 폰트를 연결시킨 변수 fontObj를 이용해 render() 함수를 통해 글씨를 화면 상에 출력할 수 있습니다.
render(message, Anti-Aliasing, color, backgroundcolor)의 4개의 인자를 전달받으며,
Anti-Aliasing이 True일 경우 안티앨리어싱을 적용해 부드러운 글자를 출력하며, False를 전달할 경우 안티앨리어싱이 적용되지 않아 다소 딱딱한 글씨체를 화면 상에 출력합니다.

2016년 5월 9일 월요일

Pygame (3) 그림파일 가져오기, 객체 이동

간단한 고양이 PNG 파일을 이용하여 고양이가 움직이도록 한다.

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
             direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

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

    pygame.display.update()
    #fpsClock.tick(FPS)

다음과 같은 코드를 실행하면 흰 화면에 고양이가 돌아다니는 모습을 볼 수 있다.



 pygame.time.Clock()을 이용해 clock(fpsClock)을 만들어준 후, fpsClock.tick(FPS)를 pygame.display.update() 뒤에 배치해 애니메이션의 속도를 조절한다.
FPS가 낮을수록 프로그램은 느리게 진행되며, 높을수록 프로그램은 빠르게 진행된다.
* (clock_name).tick()이 없는 경우, 파이썬 프로그램은 있는 힘껏 프로그램을 진행시킨다. 직접 뺀 채로 컴파일 해보는 것을 추천한다.




pygame.image.load()를 이용해 사진 파일을 불러와서 변수에 저장한 후, 다른 함수를 이용할 수 있다.
불러오려는 파일은 AppData 폴더 속 Python 폴더에 있거나, 실행 코드 파일과 같은 폴더 내에 있어야 한다. 그렇지 않은 경우 에러가 발생한다.

DISPLAYSURF.blit(catImg, (catx, caty))
blit() 함수를 이용하여 catImg를 DISPLAYSURF 위에 복사했다.
blit() 함수는 두개의 인자를 받는데, 첫 번째는 복사할 객체이고, 두 번째는 객체를 복사할 위치의 좌표이다.

Pygame (2) 픽셀, 도형 다루기

간단한 선분, 오각형, 원, 타원, 픽셀을 다뤄보고, 색을 조정해본다.

import pygame, sys
from pygame.locals import *
pygame.init()

# set up the window
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Drawing')

# set up the colorsBLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

# draw on the surface object
DISPLAYSURF.fill(WHITE)
pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, RED, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50))

pixObj = pygame.PixelArray(DISPLAYSURF)
pixObj[480][380] = BLACK
pixObj[482][382] = BLACK
pixObj[484][384] = BLACK
pixObj[486][386] = BLACK
pixObj[488][388] = BLACK
del pixObj

while True: # main game loop    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

fill(color) : color 색깔로 화면 전체를 채운다.

pygame.draw.polygon(surface, color, pointlist, width) : 오각형을 그린다. 어떤 표면 위에 어떤 색으로, 어떤 점에서 찍을 지 인자를 전달해주면 된다. width는 옵션으로, 인자를 전달하면 오각형의 외곽선을 나타내며, 인자를 전달하지 않으면 내부가 color로 채워진다.

pygame.draw.line(surface, color, start_point, end_point, width) : 선분을 그린다. polygon 함수와 유사하며, 시작점과 끝점을 인자로 받는다.

pygame.draw.lines(surface, color, closed, pointlist, width) : 선분들을 그린다. pointlist가 선분들의 한 점이 되며, closed가 True인 경우 맨 마지막 점과 처음 점을 잇는 선분이 그려지고, False일 경우 그렇지 않다.

pygame.draw.circle(surface, color, center_point, radius, width) : 원을 그린다. 중심과 반지름을 인자로 받는다.

pygame.draw.ellipse(surface, color, bounding_rectangle, width) : 타원을 그린다. bounding_rectangle에 rectangle_tuple을 전달하면 그 직사각형에 내접하는 타원을 그린다.
* rectangle_tuple : ( x pos, y pos, width, height )

pygame.draw.rect(surface, color, rectangle_tuple, width) : 직사각형을 그린다. 

pygame.PixelArray(surface)를 이용해 surface의 픽셀을 변경시킬 수 있다. 수행하려는 작업이 끝나면 del을 이용해 지워서 unlock을 해 줘야 한다. 그렇지 않을 경우, blit()을 이용해 변경된 픽셀을 변경하려 할 때 오류가 발생한다.

Pygame (1) 시작하기

pygame을 이용한 게임 코딩에 도전하기 전에, 기본적인 틀을 알아보기 위해 게임 창을 띄우는 간단한 코드를 작성해 보았다.


import pygame
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

미리 설치했던 pygame 파일을 참조한 후,

display.set_mode()를 이용해 창의 크기를 설정한다.
display.set_caption()을 이용해 창의 제목에 삽입할 문구를 넣는다.

while문 안에서 event.type을 변경하는 별도의 문장이 없으므로
비어있는 화면이 프로그램을 종료할때까지 떠 있는다.



실행 화면.

* 참고
기존 shell에서 입출력을 위해 쓰는 함수인 print()나 input()은 CLI(Call Level Interface) 프로그램을 위한 함수이므로 Pygame상에서 입력이나 출력을 위해서는 다른 별도의 함수를 써야 한다.

Windows python 3.5 pygame 설치

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

http://dogdriip.tistory.com/3

첫 번째 링크에 들어가 자신에게 맞는 파이썬 버전과 32bit(or 64bit)를 확인한 후 다운을 받아줍니다.

그러면 .whl파일을 다운받을 수 있는데,

두 번째 링크를 참조하여 명령 프롬프트를 이용하여 파일을 설치할 수 있습니다.
(확장자를 빼먹을 경우 설치에 실패합니다)

2016년 4월 30일 토요일

파이썬 shortcut circuit

파이썬에서 shortcut circuit을 이용하여 두 연산 중 어느 쪽이 빠른지 짐작해볼 수 있다.

https://www.acmicpc.net/problem/1463

아래 두 코드와 그 실행 결과는 위 알고리즘 문제에 따라서 만들었으며,
그 결과로 동일한 알고리즘에 동일한 입력 값을 입력하였을 때
조건문의 순서에 따라서도 알고리즘의 효율성이 달라지는 것을 확인할 수 있다.

python 3.5.2