可扩展:
多个食物:p可以改成数组一次性出现多个食物 修改判断== 为 in
按键加速:时间控制使用了自定义事件。修改while 1 上方时间 增加按空格加速可以再定义一个事件N=pygame.USEREVENT+1 时间设置为50 按下空格修改为 N 抬起空格事件修改回pygame.USEREVENT
import random
import sys
import pygame
class Snake:
p=(random.randint(0,49),random.randint(0,49))
def __init__(self):
self.body=[(25,25)] #500*500
self.d_x=0
self.d_y=-1
def move(self):
head=self.body[0]
self.body.insert(0,(head[0]+self.d_x,head[1]+self.d_y))
if self.body[0]==Snake.p:
Snake.p=(random.randint(0,49),random.randint(0,49))
else:
self.body.pop(len(self.body)-1)
pygame.init()
root=pygame.display.set_mode((500,500))
a=Snake()
pygame.time.set_timer(pygame.USEREVENT,100)
while 1:
for e in pygame.event.get():
if e.type==pygame.KEYDOWN:
if e.key==pygame.K_UP:
a.d_y=-1
a.d_x=0
if e.key == pygame.K_DOWN:
a.d_y = 1
a.d_x = 0
if e.key == pygame.K_LEFT:
a.d_y = 0
a.d_x = -1
if e.key == pygame.K_RIGHT:
a.d_y = 0
a.d_x = 1
if e.type==pygame.USEREVENT:
a.move()
if e.type==pygame.QUIT:
pygame.quit()
sys.exit()
root.fill("black")
for i in a.body:
pygame.draw.rect(root,"lightgreen",(i[0]*10,i[1]*10,10,10))
pygame.draw.rect(root, "red", (Snake.p[0] * 10, Snake.p[1] * 10, 10, 10))
pygame.display.update()
#print(a.body)
if a.body[0][0]>50 or a.body[0][0]<0:
pygame.quit()
if a.body[0][1]>50 or a.body[0][1]<0:
print(a.body)
pygame.quit()
kk=a.body.copy().pop(0)
if a.body[0] in kk:
pygame.quit()