貪喫蛇006(如何讓蛇喫到食物呢)

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

#窗口變量
windows_width = 800
windows_height = 480
cell_size = 20 #方塊大小
map_width=windows_width//cell_size
map_hight = windows_height//cell_size

#設置顏色變量
white = (255,255,255)
red = (255,0,0)
red2=(201,23,12)
blue = (0,0,255)
blue2 = (4,23,120)
dark_gray = (100,100,100)
green = (0, 255, 0)

snake_speed = 15 # 貪喫蛇的速度


#初始化pygame(退出遊戲時記得使用pygame.quit())
pygame.init()
screen = pygame.display.set_mode((windows_width,windows_height))
screen.fill(blue2)
pygame.display.set_caption("PYTHON 貪喫蛇98")
#通過時鐘對象控制刷新頻率
snake_speed_clock = pygame.time.Clock()

#開始界面
gamestart = pygame.image.load('gamestart.png')
gamestart = pygame.transform.scale(gamestart,(windows_width,windows_height)) # transform.scale縮放圖片
screen.blit(gamestart,(0,0))  #blit 第一個參數:要顯示的元素,第二個參數:座標

font = pygame.font.Font('myfont.ttf',60)
tip = font.render("貪喫蛇",True,red) #渲染
screen.blit(tip,(300,30))

font = pygame.font.Font('my_pygame/resources/font/myfont.ttf',40)
tip = font.render("按任意鍵開始遊戲(按ESC退出遊戲)",True,blue) #設定需要顯示的文字,True代表打開抗鋸齒(字體顯示平滑),blue顏色
screen.blit(tip, (100, 300))

#修改屏幕對象後,記得更新操作
pygame.display.update()

#播放背景音樂,set_volume控制音量大小
pygame.mixer.music.stop()
pygame.mixer.music.load("bensound-endlessmotion.wav")
pygame.mixer.music.set_volume(0.9)
pygame.mixer.music.play(-1)

# 使用變量i,巧妙的控制while循環
i=1
while i>0:
    for event in pygame.event.get():
        if event.type == pygame.constants.QUIT:
            print("按關閉鍵退出")
            pygame.quit()
            sys.exit()
        elif event.type == pygame.constants.KEYDOWN:
            if event.key == pygame.constants.K_ESCAPE:
                print("按ESC退出")
                pygame.quit()
                sys.exit()
            else:
                i=0  # 這裏不能使用break,思考一下爲什麼呢?

#摁任意鍵進入遊戲頁面
#方向鍵默認向右(注意不能向左,因爲蛇頭默認在最右邊,向左走,意味着蛇頭碰到蛇身,遊戲會退出)
direction = "RIGHT"
# # 設置貪喫蛇的位置
# # 初始貪喫蛇,默認5節蛇身
startx = starty = 20
snake_coords = [{'x': startx, 'y': starty},
                {'x': startx - 1, 'y': starty},
                {'x': startx - 2, 'y': starty},
                {'x': startx - 3, 'y': starty},
                {'x': startx - 4, 'y': starty}]
food = {"x": 10, "y": 9}
while True:

    # 監聽鍵盤事件(w上,s下,a左,d右)
    # 判斷方向爲上時,按下鍵無效、爲左時,按右鍵無效(方向爲下,右時同理)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT or event.key == K_a) and direction != "RIGHT":
                direction = "LEFT"
            elif (event.key == K_RIGHT or event.key == K_d) and direction != "LEFT":
                direction = "RIGHT"
            elif (event.key == K_UP or event.key == K_w) and direction != "DOWN":
                direction = "UP"
            elif (event.key == K_DOWN or event.key == K_s) and direction != "UP":
                direction = "DOWN"
            elif event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    if direction == "RIGHT":
        newHead = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']}  # 方向向右
    elif direction == "LEFT":
        newHead = {'x': snake_coords[0]['x'] - 1, 'y': snake_coords[0]['y']}
    elif direction == "UP":
        newHead = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y'] - 1}
    elif direction == "DOWN":
        newHead = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y'] + 1}

    # 不管有沒有喫到食物,都要插入新的蛇頭
    snake_coords.insert(0, newHead)
    # 喫到食物邏輯:判斷蛇頭座標與食物座標是否相同
    if snake_coords[0]["x"] == food["x"] and snake_coords[0]["y"] == food["y"]:
        food_x = random.randint(0, map_width - 1)
        food_y = random.randint(0, map_hight - 1)
        food = {'x': food_x, 'y': food_y}  # 食物隨機位置
    else: #如果沒有喫到食物,刪除蛇尾
        del snake_coords[-1]

    screen.fill(white)

    # 畫網格線  # draw.line五個參數,surface,顏色,起始點,終止點,線寬(默認爲1)
    for x in range(0, windows_width, cell_size):  # 垂直線,每隔cell_size(20)劃一條垂直線
        pygame.draw.line(screen, blue2, (x, 0), (x, windows_height))
    for y in range(0, windows_height, cell_size):  # 水平線,每隔cell_size(20)劃一條水平線
        pygame.draw.line(screen, blue2, (0, y), (windows_width, y))



    # 畫蛇
    for coord in snake_coords:  # 變量列表,得到三節蛇身的座標
        x = coord['x'] * cell_size
        y = coord['y'] * cell_size
        oneRect = pygame.Rect(x, y, cell_size, cell_size)
        # pygame.Rect四個參數,x,y座標,寬,高
        pygame.draw.rect(screen, red2, oneRect)
        # draw.rect四個參數Surface,顏色,上面的Rect(x,y,寬,高), 線條寬度(默認0)
        oneInnerRect = pygame.Rect(x + 2, y + 2, cell_size - 4, cell_size - 4)
        # 爲了美觀,內部再畫一個方塊
        pygame.draw.rect(screen, blue, oneInnerRect)

    #畫食物
    x = food['x'] * cell_size
    y = food['y'] * cell_size
    foodRect = pygame.Rect(x, y, cell_size, cell_size)
    pygame.draw.rect(screen, dark_gray, foodRect)
    foodInnerRect = pygame.Rect(x + 3, y + 3, cell_size - 6, cell_size - 6)
    pygame.draw.rect(screen, green, foodInnerRect)

    pygame.display.update()
    snake_speed_clock.tick(snake_speed)

 

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