貪喫蛇002(增加退出遊戲事件)

  

 

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)


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")

#開始界面
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()

# 使用變量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(blue2)


    pygame.display.update()

 

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