当前位置:首页 » 编程语言 » python简易代码

python简易代码

发布时间: 2024-11-20 01:17:41

python有趣的编程代码

classPoint:
row=0
col=0
def__init__(self,row,col):
self.row=row
self.col=col

def(self):
returnPoint(row=self.row,col=self.col)


#初始框架
importpygame
importrandom

#初始化
pygame.init()
W=800
H=600

ROW=30
COL=40

size=(W,H)
window=pygame.display.set_mode(size)
pygame.display.set_caption('贪吃蛇')

bg_color=(255,255,255)
snake_color=(200,200,200)

head=Point(row=int(ROW/2),col=int(COL/2))
head_color=(0,128,128)

snakes=[
Point(row=head.row,col=head.col+1),
Point(row=head.row,col=head.col+2),
Point(row=head.row,col=head.col+3)
]

#生成食物
defgen_food():
while1:
pos=Point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))

#
is_coll=False

#是否跟蛇碰上了
ifhead.row==pos.rowandhead.col==pos.col:
is_coll=True

#蛇身子
forsnakeinsnakes:
ifsnake.row==pos.rowandsnake.col==pos.col:
is_coll=True
break

ifnotis_coll:
break

returnpos


#定义坐标


food=gen_food()
food_color=(255,255,0)direct='left'#left,right,up,down

#
defrect(point,color):
cell_width=W/COL
cell_height=H/ROW

left=point.col*cell_width
top=point.row*cell_height

pygame.draw.rect(
window,color,
(left,top,cell_width,cell_height)
)
pass

#游戏循环
quit=True
clock=pygame.time.Clock()
whilequit:
#处理事件
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
quit=False
elifevent.type==pygame.KEYDOWN:
ifevent.key==273orevent.key==119:
ifdirect=='left'ordirect=='right':
direct='up'
elifevent.key==274orevent.key==115:
ifdirect=='left'ordirect=='right':
direct='down'
elifevent.key==276orevent.key==97:
ifdirect=='up'ordirect=='down':
direct='left'
elifevent.key==275orevent.key==100:
ifdirect=='up'ordirect=='down':
direct='right'

#吃东西
eat=(head.row==food.rowandhead.col==food.col)

#重新产生食物
ifeat:
food=gen_food()

#处理身子
#1.把原来的头,插入到snakes的头上
snakes.insert(0,head.())
#2.把snakes的最后一个删掉
ifnoteat:
snakes.pop()

#移动
ifdirect=='left':
head.col-=1
elifdirect=='right':
head.col+=1
elifdirect=='up':
head.row-=1
elifdirect=='down':
head.row+=1

#检测
dead=False
#1.撞墙
ifhead.col<0orhead.row<0orhead.col>=COLorhead.row>=ROW:
dead=True

#2.撞自己
forsnakeinsnakes:
ifhead.col==snake.colandhead.row==snake.row:
dead=True
break

ifdead:
print('死了')
quit=False

#渲染——画出来
#背景
pygame.draw.rect(window,bg_color,(0,0,W,H))

#蛇头
forsnakeinsnakes:
rect(snake,snake_color)
rect(head,head_color)
rect(food,food_color)

#
pygame.display.flip()

#设置帧频(速度)
clock.tick(8)

#收尾工作

这是一个简易版贪吃蛇的代码,虽然结构简单,但是该有的功能都是完整的,可玩性也不错

热点内容
安装时编译 发布:2024-11-20 03:22:10 浏览:447
怎么看电脑的缓存 发布:2024-11-20 03:08:28 浏览:152
c语言api文档 发布:2024-11-20 03:08:28 浏览:867
汽车在线密码是什么意思 发布:2024-11-20 03:04:43 浏览:3
db2数据库插入 发布:2024-11-20 02:59:18 浏览:731
android二维码扫描代码 发布:2024-11-20 02:56:19 浏览:798
aspcms上传图片 发布:2024-11-20 02:56:10 浏览:811
电脑组装怎么选配置 发布:2024-11-20 02:55:38 浏览:195
javalinux乱码 发布:2024-11-20 02:48:11 浏览:469
服务器如何查看种子 发布:2024-11-20 02:47:35 浏览:268