欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Pygame实现简单的贪吃蛇游戏

程序员文章站 2022-03-09 23:03:27
目录导入相关的包设置屏幕大小以及基本参数设置贪吃蛇的位置,以及移动的大小绘制蛇让蛇动起来实现贪吃蛇拐弯实现随机食物吃食物完整代码 导入相关的包import pygame, sys, randomfro...

导入相关的包

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

设置屏幕大小以及基本参数

设置屏幕大小为400*400,mainclock = pygame.time.clock()用来设置时间同步,不会根据计算机的运行来决定运行多少次, mainclock.tick(1) 一秒只会运行一次,设置了屏幕的底色为白色。

# 定义屏幕的宽高
width = 400
height = 400
# 初始化屏幕 设置窗口标题
surface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('贪吃蛇')

pygame.init()
mainclock = pygame.time.clock()

# 定义使用的颜色
black = (0, 0, 0)
green = (0, 255, 0)
white = (255, 255, 255)


while true:
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()

    surface.fill(white)
    pygame.display.update()
    mainclock.tick(1)

基于Pygame实现简单的贪吃蛇游戏

设置贪吃蛇的位置,以及移动的大小

这里设置了贪吃蛇的长度和起始位置,和食物和蛇的宽度,这里必须设置为可以被食物和蛇的宽度整除的数,这样才能保证蛇能到任意的位置

# 设置蛇的初始长度
snakewidth = 4
# 设置蛇的起始位置为(40,40)
snakex = 40
snakey = 40
# 食物和蛇的宽度设置为8
foodsnakewidth = 8
# 定义四个方向
moveleft = false
moveright = false
moveup = false
movedown = false
# 定义初始的方向
moveright = true


def getsnake():
    # 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40)
    # 因为贪吃蛇会拐弯,所以将蛇设置为一个列表
    snake = []
    for i in range(snakewidth):
        snake.append(pygame.rect(snakex + i * foodsnakewidth, snakey, foodsnakewidth, foodsnakewidth))
    return snake


# 贪吃蛇
snake = getsnake()

绘制蛇

surface.fill(white)
for s in snake:
    pygame.draw.rect(surface, black, s)

让蛇动起来

这里将蛇列表最后一位移除,然后将第一位的位置根据方向加减坐标

    snake.pop()
    newtop = copy.deepcopy(snake[0])
    # 改变蛇的位置
    if moveright:
        newtop.left += foodsnakewidth
    if moveleft:
        newtop.left -= foodsnakewidth
    if moveup:
        newtop.top -= foodsnakewidth
    if movedown:
        newtop.top += foodsnakewidth

    snake.insert(0, newtop)

基于Pygame实现简单的贪吃蛇游戏

这样会有一个问题,如果超出屏幕呢,我们将超出屏幕,那么就会消失,我们只需要你移动第一个元素的时候,如果超出则将元素移动另一个位置。

    # 改变蛇的位置
    if moveright:
        if newtop.right == width:
            newtop.left = 0
        else:
            newtop.left += foodsnakewidth
    if moveleft:
        if newtop.left == 0:
            newtop.right == width
        else:
            newtop.left -= foodsnakewidth
    if moveup:
        if newtop.top == 0:
            newtop.bottom = height
        else:
            newtop.top -= foodsnakewidth
    if movedown:
        if newtop.bottom == height:
            newtop.top = 0
        else:
            newtop.top += foodsnakewidth

实现贪吃蛇拐弯

为了实现对应的功能,我们将方向变量改为一个变量,这样我们方便修改方向

# 定义四个方向
# moveleft moveright moveup movedown
# 定义初始的方向
snakedirection = "moveright"
  ----
  省略的代码
  ----
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()
        if event.type == keydown:
            if event.key == k_left:
                if snakedirection == "moveright":
                    snake.reverse()
                snakedirection = "moveleft"
            if event.key == k_right:
                if snakedirection == "moveleft":
                    snake.reverse()
                snakedirection = "moveright"
            if event.key == k_up:
                if snakedirection == "movedown":
                    snake.reverse()
                snakedirection = "moveup"
            if event.key == k_down:
                if snakedirection == "moveup":
                    snake.reverse()
                snakedirection = "movedown"

为了方便看到效果,我将mainclock.tick(1) 设置为mainclock.tick(3)

基于Pygame实现简单的贪吃蛇游戏

实现随机食物

这里用了很啰嗦的代码,我自己也看不下去,有点含糊,这里为了简单只设计了一个食物,遍历屏幕上不是贪吃蛇的可以放食物的集合,然后随机生成一个食物。

    if len(foods) < foodnum:

        canfoodcoll = []
        # 获取当前不是贪吃蛇的位置集合
        for x in range(sizenum):
            for y in range(sizenum):
                foodexist = true
                for sn in snake:
                    if x * foodsnakewidth == sn.left and y * foodsnakewidth == sn.top:
                        foodexist = false
                        break
                if foodexist:
                    canfoodcoll.append({'x': x, 'y': y})
        f = canfoodcoll[random.randint(0, len(canfoodcoll))]
        foods.append(pygame.rect(f['x'], f['y'], foodsnakewidth, foodsnakewidth))

基于Pygame实现简单的贪吃蛇游戏

吃食物

这里用 colliderect判断二者是否相撞,然后食物集合置空,不减去贪吃蛇集合的最后一个元素。

    if len(foods) < foodnum:

        canfoodcoll = []
        # 获取当前不是贪吃蛇的位置集合
        for x in range(sizenum):
            for y in range(sizenum):
                foodexist = true
                for sn in snake:
                    if x * foodsnakewidth == sn.left and y * foodsnakewidth == sn.top:
                        foodexist = false
                        break
                if foodexist:
                    canfoodcoll.append({'x': x, 'y': y})
        f = canfoodcoll[random.randint(0, len(canfoodcoll))]
        foods.append(pygame.rect(f['x'] * foodsnakewidth, f['y'] * foodsnakewidth, foodsnakewidth, foodsnakewidth))
        print(f['x'])
        print(f['y'])
    else:
        if newtop.colliderect(foods[0]):
            foods = []
            eatflg = true
        print('xxx')

基于Pygame实现简单的贪吃蛇游戏

完整代码 

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

# 定义屏幕的宽高
width = 400
height = 400
# 初始化屏幕 设置窗口标题
surface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('贪吃蛇')

pygame.init()
mainclock = pygame.time.clock()

# 定义使用的颜色
black = (0, 0, 0)
green = (0, 255, 0)
white = (255, 255, 255)

# 设置蛇的初始长度
snakewidth = 4
# 设置蛇的起始位置为(40,40)
snakex = 40
snakey = 40
# 食物和蛇的宽度设置为8
foodsnakewidth = 8
# 定义四个方向
# moveleft moveright moveup movedown
# 定义初始的方向
snakedirection = "moveright"

# 食物区间
foods = []
# 用去宽度处以对应的 大小,减去1 就是食物矩形起点可以存在的区间
#sizenum = height / foodsnakewidth - 1
# 这里为了减少计算
sizenum = 39
# 为了简单我们只设置一个食物
foodnum = 1


def getsnake():
    # 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40)
    # 因为贪吃蛇会拐弯,所以将蛇设置为一个列表
    snake = []
    for i in range(snakewidth):
        snake.append(pygame.rect(snakex + i * foodsnakewidth, snakey, foodsnakewidth, foodsnakewidth))
    return snake


# 贪吃蛇
snake = getsnake()

while true:

    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()
        if event.type == keydown:
            if event.key == k_left:
                if snakedirection == "moveright":
                    snake.reverse()
                snakedirection = "moveleft"
            if event.key == k_right:
                if snakedirection == "moveleft":
                    snake.reverse()
                snakedirection = "moveright"
            if event.key == k_up:
                if snakedirection == "movedown":
                    snake.reverse()
                snakedirection = "moveup"
            if event.key == k_down:
                if snakedirection == "moveup":
                    snake.reverse()
                snakedirection = "movedown"
    surface.fill(white)
    for s in snake:
        pygame.draw.rect(surface, black, s)
    for f in foods:
        pygame.draw.rect(surface, green, f)
    pygame.display.update()


    # 是否吃了食物
    eatflg = false

    newtop = copy.deepcopy(snake[0])
    # 改变蛇的位置
    if snakedirection == "moveright":
        if newtop.right == width:
            newtop.left = 0
        else:
            newtop.left += foodsnakewidth
    if snakedirection == "moveleft":
        if newtop.left == 0:
            newtop.right = width
        else:
            newtop.left -= foodsnakewidth
    if snakedirection == "moveup":
        if newtop.top == 0:
            newtop.bottom = height
        else:
            newtop.top -= foodsnakewidth
    if snakedirection == "movedown":
        if newtop.bottom == height:
            newtop.top = 0
        else:
            newtop.top += foodsnakewidth

    if len(foods) < foodnum:

        canfoodcoll = []
        # 获取当前不是贪吃蛇的位置集合
        for x in range(sizenum):
            for y in range(sizenum):
                foodexist = true
                for sn in snake:
                    if x * foodsnakewidth == sn.left and y * foodsnakewidth == sn.top:
                        foodexist = false
                        break
                if foodexist:
                    canfoodcoll.append({'x': x, 'y': y})
        f = canfoodcoll[random.randint(0, len(canfoodcoll))]
        foods.append(pygame.rect(f['x'] * foodsnakewidth, f['y'] * foodsnakewidth, foodsnakewidth, foodsnakewidth))
        print(f['x'])
        print(f['y'])
    else:
        if newtop.colliderect(foods[0]):
            foods = []
            eatflg = true
        print('xxx')



    snake.insert(0, newtop)
    if not eatflg:
        snake.pop()

    mainclock.tick(3) 

以上就是基于pygame实现简单的贪吃蛇游戏的详细内容,更多关于pygame 贪吃蛇游戏的资料请关注其它相关文章!

相关标签: Pygame 贪吃蛇