首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >贪吃蛇程序代码python_Python贪吃蛇代码

贪吃蛇程序代码python_Python贪吃蛇代码

作者头像
全栈程序员站长
发布2022-09-22 13:37:08
发布2022-09-22 13:37:08
1.1K0
举报

大家好,又见面了,我是你们的朋友全栈君。

import sys, pygame

from pygame.locals import *

from random import randrange

up =lambda x:(x[0]-1,x[1])

down = lambda x :(x[0]+1,x[1])

left = lambda x : (x[0],x[1]-1)

right = lambda x : (x[0],x[1]+1)

tl = lambda x :x<3 and x+1 or 0

tr = lambda x :x==0 and 3 or x-1

dire = [up,left,down,right]

move = lambda x,y:[y(x[0])]+x[:-1]

grow = lambda x,y:[y(x[0])]+x

s = [(5,5),(5,6),(5,7)]

d = up

food = randrange(0,30),randrange(0,40)

FPSCLOCK=pygame.time.Clock()

pygame.init()

pygame.display.set_mode((800,600))

pygame.mouse.set_visible(0)

screen = pygame.display.get_surface()

screen.fill((0,0,0))

times=0.0

while True:

time_passed = FPSCLOCK.tick(30)

if times>=150:

times =0.0

s = move(s,d)

else:

times +=time_passed

for event in pygame.event.get():

if event.type == QUIT:

sys.exit()

if event.type == KEYDOWN and event.key == K_UP:

s = move(s,d)

if event.type == KEYDOWN and event.key == K_LEFT:

d=dire[tl(dire.index(d))]

if event.type == KEYDOWN and event.key == K_RIGHT:

d=dire[tr(dire.index(d))]

if s[0]==food:

s = grow(s,d)

food =randrange(0,30),randrange(0,40)

if s[0] in s[1:] or s[0][0]<0 or s[0][0]

>= 30 or s[0][1]<0 or

s[0][1]>=40:

break

screen.fill((0,0,0))

for r,c in s:

pygame.draw.rect(screen,(255,0,0),(c*20,r*20,20,20))

pygame.draw.rect(screen,(0,255,0),(food[1]*20,food[0]*20,20,20))

pygame.display.update()

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/169555.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档