python簡易代碼
發布時間: 2024-11-20 01:17:41
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)
#收尾工作
這是一個簡易版貪吃蛇的代碼,雖然結構簡單,但是該有的功能都是完整的,可玩性也不錯
熱點內容