2014年6月19日 星期四








PDF


# Wormy (a Nibbles clone)
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
# Released under a "Simplified BSD" license

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

FPS = 15
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
CELLSIZE = 20
assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)

#             R    G    B
白色     = (255, 255, 255)
黑色     = (  0,   0,   0)
紅色       = (255,   0,   0)
綠色     = (  0, 255,   0)
暗綠色 = (  0, 155,   0)
暗灰色  = ( 40,  40,  40)
背景顏色 = 黑色

上 = 'up'
下 = 'down'
左 = 'left'
右 = 'right'

頭 = 0 # syntactic sugar: index of the worm's head

def main():
    global 偵數, 現象, 字型

    pygame.init()
    偵數 = pygame.time.Clock()
    顯示 = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    字型 = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('Wormy')

    顯示開始畫面()
    while True:
        執行遊戲()
        遊戲結束畫面()


def 執行遊戲():
    # Set a random start point.
    開始x = random.randint(5, CELLWIDTH - 6)
    開始y = random.randint(5, CELLHEIGHT - 6)
    蟲座標 = [{'x': 開始x,     'y': 開始y},
                  {'x': 開始x - 1, 'y': 開始y},
                  {'x': 開始x - 2, 'y': 開始y}]
    方向 = 右
    # Start the apple in a random place.
    apple = 取得隨機位置()

    while True: # main game loop
        for event in pygame.event.get(): # event handling loop
            if event.type == QUIT:
                終止()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT or event.key == K_a) and 方向 != 右:
                    方向 = 左
                elif (event.key == K_RIGHT or event.key == K_d) and 方向 != 左:
                    方向 = 右
                elif (event.key == K_UP or event.key == K_w) and 方向 != 下:
                    方向 = 上
                elif (event.key == K_DOWN or event.key == K_s) and 方向 != 上:
                    方向 = 下
                elif event.key == K_ESCAPE:
                    終止()

        # check if the worm has hit itself or the edge
        if 蟲座標[頭]['x'] == -1 or 蟲座標[頭]['x'] == CELLWIDTH or 蟲座標[頭]['y'] == -1 or 蟲座標[頭]['y'] == CELLHEIGHT:
            return # game over
        for 蟲身體 in 蟲座標[1:]:
            if 蟲身體['x'] == 蟲座標[頭]['x'] and 蟲身體['y'] == 蟲座標[頭]['y']:
                return # game over

        # check if worm has eaten an apply
        if 蟲座標[頭]['x'] == apple['x'] and 蟲座標[頭]['y'] == apple['y']:
            # don't remove worm's tail segment
            apple = 取得隨機位置() # set a new apple somewhere
        else:
            del 蟲座標[-1] # remove worm's tail segment

        # move the worm by adding a segment in the 方向 it is moving
        if 方向 == 上:
            新的頭 = {'x': 蟲座標[頭]['x'], 'y': 蟲座標[頭]['y'] - 1}
        elif 方向 == 下:
            新的頭 = {'x': 蟲座標[頭]['x'], 'y': 蟲座標[頭]['y'] + 1}
        elif 方向 == 左:
            新的頭 = {'x': 蟲座標[頭]['x'] - 1, 'y': 蟲座標[頭]['y']}
        elif 方向 == 右:
            新的頭 = {'x': 蟲座標[頭]['x'] + 1, 'y': 蟲座標[頭]['y']}
        蟲座標.insert(0, 新的頭)
        顯示.fill(背景顏色)
        畫邊線()
        畫蟲(蟲座標)
        畫蘋果(apple)
        畫分數(len(蟲座標) - 3)
        pygame.display.update()
        偵數.tick(FPS)

def 顯示按鈕訊息():
    顯示按鈕 = 字型.render('Press a key to play.', True, 暗灰色)
    按鈕唷 = 顯示按鈕.get_rect()
    按鈕唷.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
    顯示.blit(顯示按鈕, 按鈕唷)


def 確認按鍵():
    if len(pygame.event.get(QUIT)) > 0:
        終止()

    按鍵觸發事件 = pygame.event.get(KEYUP)
    if len(按鍵觸發事件) == 0:
        return None
    if 按鍵觸發事件[0].key == K_ESCAPE:
        終止()
    return 按鍵觸發事件[0].key


def 顯示開始畫面():
    標題字 = pygame.font.Font('freesansbold.ttf', 100)
    標題圖字一 = 標題字.render('Wormy!', True, 白色, 暗綠色)
    標題圖字二 = 標題字.render('Wormy!', True, 綠色)

    等級一 = 0
    等級二 = 0
    while True:
        顯示.fill(背景顏色)
        旋轉圖字一 = pygame.transform.rotate(標題圖字一, 等級一)
        旋轉圖字一唷 = 旋轉圖字一.get_rect()
        旋轉圖字一唷.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        顯示.blit(旋轉圖字一, 旋轉圖字一唷)

        旋轉圖字二 = pygame.transform.rotate(標題圖字二, 等級二)
        旋轉圖字二唷 = 旋轉圖字二.get_rect()
        旋轉圖字二唷.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        顯示.blit(旋轉圖字二, 旋轉圖字二唷)

        顯示按鈕訊息()

        if 確認按鍵():
            pygame.event.get() # clear event queue
            return
        pygame.display.update()
        偵數.tick(FPS)
        等級一 += 3 # rotate by 3 degrees each frame
        等級二 += 7 # rotate by 7 degrees each frame


def 終止():
    pygame.quit()
    sys.exit()


def 取得隨機位置():
    return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}


def 遊戲結束畫面():
    遊戲結束字樣 = pygame.font.Font('freesansbold.ttf', 150)
    遊戲字 = 遊戲結束字樣.render('Game', True, 白色)
    結束字 = 遊戲結束字樣.render('Over', True, 白色)
    遊戲字唷 = 遊戲字.get_rect()
    結束字唷 = 結束字.get_rect()
    遊戲字唷.midtop = (WINDOWWIDTH / 2, 10)
    結束字唷.midtop = (WINDOWWIDTH / 2, 遊戲字唷.height + 10 + 25)

    顯示.blit(遊戲字, 遊戲字唷)
    顯示.blit(結束字, 結束字唷)
    顯示按鈕訊息()
    pygame.display.update()
    pygame.time.wait(500)
    確認按鍵() # clear out any key presses in the event queue

    while True:
        if 確認按鍵():
            pygame.event.get() # clear event queue
            return

def 畫分數(score):
    分數字 = 字型.render('Score: %s' % (score), True, 白色)
    分數字唷 = 分數字.get_rect()
    分數字唷.topleft = (WINDOWWIDTH - 120, 10)
    顯示.blit(分數字, 分數字唷)


def 畫蟲(蟲座標):
    for 座標 in 蟲座標:
        x = 座標['x'] * CELLSIZE
        y = 座標['y'] * CELLSIZE
        蟲的分塊 = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(顯示, 暗綠色, 蟲的分塊)
        蟲的內部分塊 = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
        pygame.draw.rect(顯示, 綠色, 蟲的內部分塊)


def 畫蘋果(座標):
    x = 座標['x'] * CELLSIZE
    y = 座標['y'] * CELLSIZE
    蘋果唷 = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
    pygame.draw.rect(顯示, 紅色, 蘋果唷)


def 畫邊線():
    for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines
        pygame.draw.line(顯示, 暗灰色, (x, 0), (x, WINDOWHEIGHT))
    for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
        pygame.draw.line(顯示, 暗灰色, (0, y), (WINDOWWIDTH, y))


if __name__ == '__main__':
    main()