import random
import sys
import pygame
#窗口變量
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)
blue = (0,0,255)
blue2 = (4,23,120)
#初始化pygame(退出遊戲時記得使用pygame.quit())
pygame.init()
screen = pygame.display.set_mode((windows_width,windows_height))
screen.fill(blue2)
pygame.display.set_caption("PYTHON 貪喫蛇98")
#開始界面
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,思考一下爲什麼呢?
#摁任意鍵進入遊戲頁面
while True:
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))
pygame.display.update()