pygame試水,寫一個貪吃蛇

Westerlund1-26發表於2019-01-21

最近學完python基礎知識,就想著做一個遊戲玩玩,於是就在https://www.pygame.org/docs/學著做了個貪吃蛇遊戲。

首先要匯入模組。

1 import pygame
2 import sys
3 from pygame.locals import *
4 import time
5 import random

首先需要一個遊戲執行的介面。

1 screen = pygame.display.set_mode((1000,700))

其次要有一條蛇和一份食物。

這是蛇:

1 snake_Position = [200,200]     #蛇的起始位置,即蛇頭的位置。
2 snakeBody = [[100,100],[90,100],[80,100]]       #列表的巢狀,每一個子列表代表一節身子的座標。

這是食物:

1 foodPosition = [500,350]      #初始時食物的位置,座標隨便設定就好,在螢幕內就行。

然後就是把蛇和食物畫出來咯~

1 for body in snakeBody:     #吧蛇的每節身子都畫出來。
2   pygame.draw.rect(screen,pygame.Color(255,255,255),Rect(body[0], body[1],10,10))

3 pygame.draw.rect(screen, pygame.Color(255,0,255),Rect(foodPosition[0], foodPosition[1], 10, 10))

再之後相辦法移動蛇身和轉彎。

        for event in pygame.event.get():
            if event.type == QUIT:
                GameOver()
            elif event.type == KEYDOWN:
                if event.key == K_RIGHT:
                    changeDirection = `right`
                if event.key == K_LEFT:
                    changeDirection = `left`
                if event.key == K_UP:
                    changeDirection = `up`
                if event.key == K_DOWN:
                    changeDirection = `down`
                    #Esc鍵
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        #確定方向
        if changeDirection == `left` and not direction == `right`:
            direction = changeDirection
        if changeDirection == `right` and not direction == `left`:
            direction = changeDirection
        if changeDirection == `up` and not direction == `down`:
            direction = changeDirection
        if changeDirection == `down` and not direction == `up`:
            direction = changeDirection
        #移動蛇頭座標 snake_Position[0]和snake_Position[1]分別代表蛇頭橫座標和縱座標
        if direction == `up`:
            snake_Position[1] -= 10
        if direction == `down`:
            snake_Position[1] += 10
        if direction == `right`:
            snake_Position[0] += 10
        if direction == `left`:
            snake_Position[0] -= 10

        #每次迴圈先增加一個蛇頭,在進行判斷,不然的話蛇不會移動
        snakeBody.insert(0,list(snake_Position))
        #吃到了食物
        if snake_Position[0] == foodPosition[0] and snake_Position[1] == foodPosition[1]:
            flag = 0
        #沒吃到食物,把增加的頭砍掉0.0
        else:
            snakeBody.pop()

需要一個遊戲結束的條件。

        #判斷蛇頭是否與身子相撞
        if len(snakeBody)>=5:
            for section in snakeBody[4:]:
                if snake_Position == section:
                    GameOver()
                else:
                    continue
        #判斷蛇頭是否與牆相撞
        if snake_Position[0] > 1000 or snake_Position[0] < 0:
            GameOver()
        elif snake_Position[1] > 700 or snake_Position[1] < 0:
            GameOver()

寫一個遊戲開始介面和結束介面就好了。

def start_text_Display():
    screen = pygame.display.set_mode((1000,700))
    text_font = pygame.font.Font(None, 90)
    text = text_font.render("Welcome to", 1, (255,0,0))
    name_font = pygame.font.Font(None, 90)
    name = name_font.render("The Game of Snake", 1, (255,0,0))
    tip_font = pygame.font.Font(None,40)
    tip = tip_font.render("Press `0` to start.    Press `ESC` to quit.", 1, (0,64,64,0))
    STARTFLAG = 1
    while STARTFLAG:
        for event in pygame.event.get():
            screen.fill(pygame.Color(0,0,0))
            screen.blit(text, (300, 250))
            screen.blit(name, (200, 350))
            screen.blit(tip, (250, 650))
            pygame.display.update()
            if event.type == KEYDOWN:
                if event.key == K_0:
                    STARTFLAG = 0
                if event.key == K_ESCAPE:
                    sys.exit()

def end_text_Display():
    screen = pygame.display.set_mode((1000,700))
    text_font = pygame.font.Font(None, 90)
    text = text_font.render("Game Over:)", 1, (255,0,0))
    name_font = pygame.font.Font(None, 40)
    name = name_font.render("Designed by SOHOYA", 1, (64,64,64,0))
    while True:
        for event in pygame.event.get():
            if event.type in (QUIT, KEYDOWN):
              sys.exit()
        screen.fill(pygame.Color(0,0,0))
        screen.blit(text, (300, 250))
        screen.blit(name, (600, 600))
        pygame.display.update()

全部原始碼如下:

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

def start_text_Display():
    screen = pygame.display.set_mode((1000,700))
    text_font = pygame.font.Font(None, 90)
    text = text_font.render("Welcome to", 1, (255,0,0))
    name_font = pygame.font.Font(None, 90)
    name = name_font.render("The Game of Snake", 1, (255,0,0))
    tip_font = pygame.font.Font(None,40)
    tip = tip_font.render("Press `0` to start.    Press `ESC` to quit.", 1, (0,64,64,0))
    STARTFLAG = 1
    while STARTFLAG:
        for event in pygame.event.get():
            screen.fill(pygame.Color(0,0,0))
            screen.blit(text, (300, 250))
            screen.blit(name, (200, 350))
            screen.blit(tip, (250, 650))
            pygame.display.update()
            if event.type == KEYDOWN:
                if event.key == K_0:
                    STARTFLAG = 0
                if event.key == K_ESCAPE:
                    sys.exit()

def end_text_Display():
    screen = pygame.display.set_mode((1000,700))
    text_font = pygame.font.Font(None, 90)
    text = text_font.render("Game Over:)", 1, (255,0,0))
    name_font = pygame.font.Font(None, 40)
    name = name_font.render("Designed by SOHOYA", 1, (64,64,64,0))
    while True:
        for event in pygame.event.get():
            if event.type in (QUIT, KEYDOWN):
              sys.exit()
        screen.fill(pygame.Color(0,0,0))
        screen.blit(text, (300, 250))
        screen.blit(name, (600, 600))
        pygame.display.update()

def GameOver():
    end_text_Display()
    pygame.quit()
    sys.exit()

# 好戲開始了:)
start = True
while start:
    #初始化
    pygame.init()
    #蛇移動的速度,即控制每個迴圈多長時間執行一次,迴圈一次,蛇移動一單位(距離需要自己設定)
    snake_speed = pygame.time.Clock()
    #遊戲介面
    screen = pygame.display.set_mode((1000,700))
    #給遊戲起個名字
    pygame.display.set_caption("Snake_Game")
    snake_Position = [200,200]     #蛇的起始位置,即蛇頭的位置
    snakeBody = [[100,100],[90,100],[80,100]]       #列表的巢狀,每一個子列表代表一節身子
    foodPosition = [500,350]      #初始時食物的位置
    flag = 1   ##標識食物是否被吃的識別符號
    direction = `down`
    changeDirection = direction
    start_text_Display()   ##遊戲開始介面
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == QUIT:
                GameOver()
            elif event.type == KEYDOWN:
                if event.key == K_RIGHT:
                    changeDirection = `right`
                if event.key == K_LEFT:
                    changeDirection = `left`
                if event.key == K_UP:
                    changeDirection = `up`
                if event.key == K_DOWN:
                    changeDirection = `down`
                    #Esc鍵
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        #確定方向
        if changeDirection == `left` and not direction == `right`:
            direction = changeDirection
        if changeDirection == `right` and not direction == `left`:
            direction = changeDirection
        if changeDirection == `up` and not direction == `down`:
            direction = changeDirection
        if changeDirection == `down` and not direction == `up`:
            direction = changeDirection
        #移動蛇頭座標 snake_Position[0]和snake_Position[1]分別代表蛇頭橫座標和縱座標
        if direction == `up`:
            snake_Position[1] -= 10
        if direction == `down`:
            snake_Position[1] += 10
        if direction == `right`:
            snake_Position[0] += 10
        if direction == `left`:
            snake_Position[0] -= 10

        #每次迴圈先增加一個蛇頭,在進行判斷,不然的話蛇不會移動
        snakeBody.insert(0,list(snake_Position))
        #吃到了食物
        if snake_Position[0] == foodPosition[0] and snake_Position[1] == foodPosition[1]:
            flag = 0
        #沒吃到食物,把增加的頭砍掉0.0
        else:
            snakeBody.pop()
        # 隨機位置產生一個食物
        if flag == 0:
            x = random.randrange(1,10)
            y = random.randrange(1,7)
            foodPosition = [int(x*100),int(y*100)]
            flag = 1

        screen.fill(pygame.Color(0,0,0))
        ##繪製蛇身和食物
        for body in snakeBody:
            pygame.draw.rect(screen, pygame.Color(255,255,255), Rect(body[0], body[1],10,10))
        pygame.draw.rect(screen, pygame.Color(255,0,255), Rect(foodPosition[0], foodPosition[1], 10, 10))
        pygame.display.update()
        #判斷蛇頭是否與身子相撞
        if len(snakeBody)>=5:
            for section in snakeBody[4:]:
                if snake_Position == section:
                    GameOver()
                else:
                    continue
        #判斷蛇頭是否與牆相撞
        if snake_Position[0] > 1000 or snake_Position[0] < 0:
            GameOver()
        elif snake_Position[1] > 700 or snake_Position[1] < 0:
            GameOver()

        #控制速度,tick(n),n表示每秒主函式main()迴圈次數,每秒迴圈次數越多看起來越流暢,但是遊戲難度更大
        snake_speed.tick(30)

這樣,貪吃蛇遊戲就做好啦,第一個遊戲,雖然好多地方不太完美,不過自己挺滿意的。

日後還要多學習學習。

 

相關文章