Bootstrap

贪吃蛇007(添加得分和游戏结束控制)

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}
score = 0
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}

    #蛇头碰到蛇身,游戏结束
    for body in snake_coords[1:]:
        if body["x"] == snake_coords[0]["x"] and body["y"] == snake_coords[0]["y"]:
            pygame.quit()
            sys.exit()

    # 不管有没有吃到食物,都要插入新的蛇头
    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}  # 食物随机位置
        score += 1
    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)

    # 绘制得分
    font = pygame.font.Font('my_pygame/resources/font/myfont.ttf', 60)
    tip = font.render("得分:" + str(score), True, red)
    screen.blit(tip, (300, 15))

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

 

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;