当前位置:首页 » 编程语言 » 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)

#收尾工作

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

热点内容
python轮廓 发布:2025-01-10 23:49:23 浏览:177
思科配置线怎么选 发布:2025-01-10 23:48:44 浏览:703
解压水晶泥 发布:2025-01-10 23:27:23 浏览:634
小米摄像头如何改wifi密码 发布:2025-01-10 23:25:14 浏览:113
阿里云服务器首页 发布:2025-01-10 23:24:15 浏览:435
win2003单网卡搭建vpn服务器搭建 发布:2025-01-10 23:21:13 浏览:355
如何制作原始传奇脚本 发布:2025-01-10 23:00:30 浏览:118
小程序免费模板源码下载 发布:2025-01-10 22:55:23 浏览:234
gradle编译jar 发布:2025-01-10 22:54:36 浏览:797
服务器搭建棋牌游戏 发布:2025-01-10 22:53:49 浏览:643