用python的pygame制作贪吃蛇游戏

起始界面,可以选择速度,开始游戏

选择开始游戏后,会进入游戏界面

界面上部分有得分情况,还有暂停、重新开始、退出按钮

点击暂停,会暂停游戏:

点击重新开始,重开游戏。点击退出,退出游戏

总体框架:

详细设计:

import math
import tkinter as tk1
import pygame
import tkinter.messagebox as tk
import random
from pygame.font import Font



#开始框
root = tk1.Tk()
root.title('贪吃蛇')
root.geometry('250x340')
snake_speed = 0#蛇移动速度
var = tk1.IntVar()
label1=tk1.Label(root,text='贪吃蛇',width=10,font=('Arial',30))
label1.pack()
label2=tk1.Label(root,text='-选择速度-',width=10,font=('Arial',20))
label2.pack()


#选择蛇的移动速度
def hit1():
    global snake_speed
    snake_speed=var.get()
b1=tk1.Radiobutton(root,text='慢',width=5,height=1,variable=var,value=2,command=hit1,font=('Arial',15))
b1.pack()
def hit2():
    global snake_speed
    snake_speed=var.get()
b2=tk1.Radiobutton(root,text='中',width=5,height=1,variable=var,value=4,command=hit2,font=('Arial',15))
b2.pack()
def hit3():
    global snake_speed
    snake_speed=var.get()
b3=tk1.Radiobutton(root,text='快',width=5,height=1,variable=var,value=6,command=hit3,font=('Arial',15))
b3.pack()


#点开始游戏,运行开始游戏函数
def cul():
    root.destroy()#关闭起始框
    pygame.init()
    pygame.mixer.init()
    #基本参数设定
    screen_width = 600
    screen_height = 600
    screen_plus = 50
    screen = pygame.display.set_mode((screen_width, screen_height+screen_plus))
    icon = pygame.image.load('D:/Python/贪吃蛇/R-C.jfif')#图标icon
    pygame.display.set_icon(icon)
    pygame.display.set_caption('贪吃蛇')
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GRAY =(192,192,192)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    snake_size = 20
    snake_x = random.randint(0, screen_width - snake_size)
    snake_y = random.randint(0, screen_height - snake_size)
    food_size = 20
    food_x = random.randint(int(food_size / 2), int(screen_width - food_size / 2))
    food_y = random.randint(int(food_size / 2), int(screen_width - food_size/2))
    snake_direction = 0
    snake_body = []
    clock = pygame.time.Clock()#刷新率管理,间接决定蛇的速度
    score = 0
    font: Font = pygame.font.SysFont('方正粗黑宋简体', 30)


#游戏框上部的按钮
    def showscore():
        text = f"得分:{score}    -暂停游戏-   -重新开始-   -退出-"
        scorerender = font.render(text, True, GREEN)
        screen.blit(scorerender, (10, 10+screen_width))

    # 蛇和食物的距离
    def distence(x1, y1, x2, y2):
        a = x1 - x2
        b = y1 - y2
        return math.sqrt(a * a + b * b)

    #绘制出蛇和食物的图像
    def draw(snake_x, snake_y, snake_body, food_x, food_y):
        for pos in snake_body:
            pygame.draw.rect(screen, BLACK, [pos[0], pos[1], snake_size, snake_size])
        pygame.draw.rect(screen, RED, [snake_x, snake_y, snake_size, snake_size])
        pygame.draw.circle(screen, WHITE, (food_x, food_y), food_size / 2, food_size)

    #运行游戏循环
    run = True
    while run:
        screen.fill(GRAY)
        pygame.draw.polygon(screen, WHITE, ((0, screen_height), (screen_width, screen_height), (screen_width,screen_height+screen_plus), (0,screen_height+screen_plus),(0,screen_height)))
        showscore()
        #加入bgm
        if pygame.mixer.music.get_busy()==0:
            pygame.mixer.music.load('D:/Python/贪吃蛇/bgm.mp3')  # 加载歌曲
            pygame.mixer.music.play()
        #键鼠事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            #鼠标事件,判断点击何种按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                (mousex, mousey) = pygame.mouse.get_pos()
                if mousex >= 134 and mousex <= 287 and mousey >= 15+screen_height and mousey <= 42+screen_height:
                    snake_direction = 5
                if mousex >= 316 and mousex <= 468 and mousey >= 15+screen_height and mousey <= 42+screen_height:
                    snake_direction = 6
                if mousex >= 500 and mousex <= 592 and mousey >= 15+screen_height and mousey <= 42+screen_height:
                    pygame.quit()
                    quit()

            #键盘事件,判断点击什么方向,用于后面移动蛇身
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and snake_direction != 'down':
                    snake_direction = 'up'
                elif event.key == pygame.K_DOWN and snake_direction != 'up':
                    snake_direction = 'down'
                elif event.key == pygame.K_LEFT and snake_direction != 'right':
                    snake_direction = 'left'
                elif event.key == pygame.K_RIGHT and snake_direction != 'left':
                    snake_direction = 'right'

        #根据上方的键盘事件,移动蛇头
        if snake_direction == 'up':
            snake_y -= snake_speed
        elif snake_direction == 'down':
            snake_y += snake_speed
        elif snake_direction == 'left':
            snake_x -= snake_speed
        elif snake_direction == 'right':
            snake_x += snake_speed

        # 蛇头坐标和食物坐标之间的距离,判断是否吃到食物
        if distence(snake_x+10, snake_y+10, food_x, food_y) <= 20:
            food_x = random.randint(int(food_size / 2), screen_width - food_size)
            food_y = random.randint(int(food_size / 2), screen_height - food_size)
            snake_body.append([snake_x, snake_y])
            score += 1

        snake_body.insert(0, [snake_x, snake_y])  # 更新蛇的身体坐标
        if len(snake_body) > 1:
            snake_body.pop()
        if snake_direction == 5:  # 暂停
            snake_x += 0
            snake_y += 0
            snake_direction = 0
            tk.showinfo("游戏暂停", "游戏暂停")
        if snake_direction == 6:  # 重新开始
            snake_x = random.randint(0, screen_width - snake_size)
            snake_y = random.randint(0, screen_height - snake_size)
            food_x = random.randint(0, screen_width - food_size)
            food_y = random.randint(0, screen_height - food_size)
            snake_body = []
            snake_direction = 0
            score = 0
        if (snake_x < 0 or snake_x > screen_width - snake_size+5 or snake_y < 0 or snake_y > screen_height - snake_size+4 or [
            snake_x, snake_y] in snake_body[1:]) and snake_direction != 0:
            snake_direction = 0
            tk.showinfo("游戏结束", "游戏结束")
            snake_x = random.randint(0, screen_width - snake_size)
            snake_y = random.randint(0, screen_height - snake_size)
            food_x = random.randint(0, screen_width - food_size)
            food_y = random.randint(0, screen_height - food_size)
            snake_body = []
            snake_direction = 0
            score = 0
        draw(snake_x, snake_y, snake_body, food_x, food_y)
        clock.tick(25)
        pygame.display.update()
b=tk1.Button(root,text='开始游戏',width=8,height=1,command=cul,font=('Arial',20))
b.pack()
def close():
    root.destroy()
bc=tk1.Button(root,text='退出游戏',width=8,height=1,command=close,font=('Arial',20))
bc.pack()
root.mainloop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值