python贪吃蛇代码开头怎么写_贪吃蛇:python代码

本文分享了一款基于Python和Pygame的简易贪吃蛇游戏代码。游戏包含背景音乐、结束音乐及图标,但存在一些待改进之处,如蛇不能往回走等。玩家需避免撞墙以延长游戏时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import sys

import pygame

import random

pygame.init()

size=width,height=800,600

screen=pygame.display.set_mode(size)

pygame.display.set_caption("贪吃蛇")

logo=pygame.image.load("gem5.png")

pygame.display.set_icon(logo)

white=(255,255,255)

black=(0,0,0)

red=(255,0,0)

blue=(0,0,255)

unit=50

fps=5

clock=pygame.time.Clock()

font=pygame.font.SysFont(None,25)

sound_Back=pygame.mixer.Sound("eat.wav")

sound_Over=pygame.mixer.Sound("gameover.wav")

def snake(body,unit):

for seat in body:

pygame.draw.rect(screen,red,[seat[0],seat[1],unit,unit])

def end():

pygame.quit()

sys.exit()

def message(msg,color):

text=font.render(msg,True,color)

screen.blit(text,[width/2,height/2])

def loop():

pygame.mixer.Sound.play(sound_Back,loops=-1)

Over=False

lead_x=width/2

lead_y=height/2

lead_x_change=0

lead_y_change=0

food_x=round((random.randrange(unit,width-unit))/unit)*unit

food_y=round((random.randrange(unit,height-unit))/unit)*unit

body=[]

length=1

while Over==False:

for event in pygame.event.get():

if event.type==pygame.QUIT:

end()

if event.type==pygame.KEYDOWN:

if event.key==pygame.K_LEFT:

lead_x_change=-unit

lead_y_change=0

elif event.key==pygame.K_RIGHT:

lead_x_change=unit

lead_y_change=0

elif event.key==pygame.K_UP:

lead_y_change=-unit

lead_x_change=0

elif event.key==pygame.K_DOWN:

lead_y_change=unit

lead_x_change=0

lead_x+=lead_x_change

lead_y+=lead_y_change

screen.fill(white)

pygame.draw.rect(screen,blue,[food_x,food_y,unit,unit])

head=[]

head.append(lead_x)

head.append(lead_y)

body.append(head)

if len(body)>length:

del body[0]

snake(body,unit)

pygame.display.update()

if lead_x==food_x and lead_y==food_y:

food_x=round((random.randrange(unit,width-unit))/unit)*unit

food_y=round((random.randrange(unit,height-unit))/unit)*unit

length+=1

clock.tick(fps)

if lead_x>=width or lead_x<=0 or lead_y>=height or lead_y<=0:

Over=True

while Over==True:

pygame.mixer.Sound.stop(sound_Back)

pygame.mixer.Sound.play(sound_Over,loops=0)

screen.fill(white)

message("game over,press C to continue or Q to quit",red)

pygame.display.update()

for event in pygame.event.get():

if event.type==pygame.QUIT:

end()

if event.type==pygame.KEYDOWN:

if event.key==pygame.K_q:

end()

if event.key==pygame.K_c:

loop()

loop()

这段代码不是完美的贪吃蛇。这个蛇可以往回走,并且碰到自己身体不会死亡,并且开局只有一格身体。(不过碰墙会死亡,而且这段代码有背景音乐、结束音乐、独立图标。但在不同电脑使用时需要先下载三组双引号中的文件,那是一个图标和两个音乐)

我再想想怎么让这个蛇不能往回走……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值