pygame編寫貪喫蛇

        一直想用pygame做一個小遊戲的,可是因爲拖延症的緣故一直沒有動,結果那天看到了一個12歲的國際友人小盆友用pygame做的一款塔防遊戲,突然感覺已經落後超級遠了,所以心血來潮做小遊戲了。高中陪伴我的遊戲就是手機裏的貪喫蛇,還記得我和老尹童鞋比拼分數的場景,所以就從貪喫蛇開始吧。

        好吧,因爲大學老師教導我們,用面向對象的語言寫程序的時候,首先考慮建立類,於是乎,我就考慮建立了snake類和food類兩個,但是我不準備在我的程序裏添加圖片,所以這兩個類最終淪爲貪喫蛇和食物它們各自的位置變換的實現了。

class snake:
    def __init__(self):
        """
        init the snake
        """
        self.poslist = [[10,10]]
    def position(self):
        """
        return the all of the snake's point
        """
        return self.poslist
    def gowhere(self,where):
        """
        change the snake's point to control the snake's moving direction
        """
        count = len(self.poslist)
        pos = count-1
        while pos > 0:
            self.poslist[pos] = copy.deepcopy(self.poslist[pos-1])
            pos -= 1
        if where is 'U':
            self.poslist[pos][1] -= 10
            if self.poslist[pos][1] < 0:
                self.poslist[pos][1] = 500
        if where is 'D':
            self.poslist[pos][1] += 10
            if self.poslist[pos][1] > 500:
                self.poslist[pos][1] = 0
        if where is 'L':
            self.poslist[pos][0] -= 10
            if self.poslist[pos][0] < 0:
                self.poslist[pos][0] = 500
        if where is 'R':
            self.poslist[pos][0] += 10
            if self.poslist[pos][0] > 500:
                self.poslist[pos][0] = 0
    def eatfood(self,foodpoint):
        """
        eat the food and add point to snake
        """
        self.poslist.append(foodpoint)

在gowhere函數中,之所以與500比較大小,是因爲我定義的窗口大小爲寬500,高500

class food:
    def __init__(self):
        """
        init the food's point
        """
        self.x = random.randint(10,490)
        self.y = random.randint(10,490)
    def display(self):
        """
        init the food's point and return the point
        """
        self.x = random.randint(10,490)
        self.y = random.randint(10,490)
        return self.position()
    def position(self):
        """
        return the food's point
        """
        return [self.x,self.y]

food 的位置是使用隨即函數隨即出來的

def main():
    moveup = False
    movedown = False
    moveleft = False
    moveright = True
    pygame.init()
    clock = pygame.time.Clock()
    width = 500
    height = 500
    screen = pygame.display.set_mode([width,height])            #1 
    restart = True
    while restart:
        sk = snake()
        fd = food()
        screentitle = pygame.display.set_caption("eat snake")   #2
        sk.gowhere('R')
        running = True
        while running:
            # fill the background is white
            screen.fill([255,255,255])                          #3

程序開始主要是做了一些初始化的工作,moveup/movedown/moveleft/moveright這四個變量使用來標註貪喫蛇的運動方向的,#1標註的那句是初始化顯示窗口的(因此所有pygame編寫的程序中,這句話有且只能調用一次),#2標註的那句是初始化標題欄顯示標題的,#3那句是用來填充整個背景爲白色

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit(0)
                # judge the down key
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        moveup = True
                        movedown = False
                        moveleft = False
                        moveright = False
                    if event.key == pygame.K_DOWN:
                        moveup = False
                        movedown = True
                        moveleft = False
                        moveright = False
                    if event.key == pygame.K_LEFT:
                        moveup = False
                        movedown = False
                        moveleft = True
                        moveright = False
                    if event.key == pygame.K_RIGHT:
                        moveup = False
                        movedown = False
                        moveleft = False 
                        moveright = True
當按下方向鍵時,設置相應的方向

            # where the snake goes
            time_pass = clock.tick(40)
            if moveup:
                sk.gowhere('U')
            if movedown:
                sk.gowhere('D')
            if moveleft:
                sk.gowhere('L')
            if moveright:
                sk.gowhere('R')
設置視頻幀數並設置貪喫蛇的移動方向

            # draw the food  
            poslist = sk.position()
            foodpoint = fd.position()
            fdrect = pygame.draw.circle(screen,[255,0,0],foodpoint,15,0)
            # draw the snafe 
            snaferect = []
            for pos in poslist:
                snaferect.append(pygame.draw.circle(screen,[255,0,0],pos,5,0))
在界面上畫上食物和貪喫蛇,其中fdrect和snaferect的存儲是後面碰撞檢測需要用到的

                # crash test if the snake eat food
                if fdrect.collidepoint(pos):
                    foodpoint = fd.display()
                    sk.eatfood(foodpoint)
                    fdrect = pygame.draw.circle(screen,[255,0,0],foodpoint,15,0)
                    break
            # crash test if the snake crash itsself
            headrect = snaferect[0]
            count = len(snaferect)
            while count > 1:
                if headrect.colliderect(snaferect[count-1]):
                    running = False
                count -= 1
            pygame.display.update()

碰撞檢測貪喫蛇是否喫到了食物,以及是否撞到了自己,pygame.display.update()是更新整個界面的意思,前面的畫圖只是畫到了區域裏,但是沒有更新到窗口,需要此句將其更新到顯示窗口

        # game over background
        pygame.font.init()
        screen.fill([100,0,0])
        font = pygame.font.Font(None,48)
        text = font.render("Game Over !!!",True,(255,0,0))
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery + 24
        screen.blit(text,textRect)
        # keydown r restart,keydown n exit
        while 1:
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    restart = True
                    del sk
                    del fd
                    break
                if event.key == pygame.K_n:
                    restart = False
                    break
            pygame.display.update()

當輸了之後,界面上顯示game over字樣,此時按下“n”退出程序,按下“r"重新開始


自己寫的這個貪喫蛇與那位國際友人寫的程序比較一下,發現我因爲懶所以沒有添加圖片和音樂,純是畫的圖,所以不需要圖片的各種操作,我覺得那個圖片跟着鼠標轉動的效果挺有意思的,以後再做別的遊戲的時候再添加吧


源碼:http://download.csdn.net/detail/vhghhd/6035283,嘿嘿

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章