最近想用动手51单片机做个贪吃的游戏机,发现没有思路索用python实现了一把(日常摸鱼),关于51贪吃蛇游戏机的事日后在更新
代码
import pygame,random
from pygame.locals import *
class Point:
row =0
col = 0
def __init__(self,row,col):
self.row=row
self.col=col
def copy(self):
return Point(row=self.row,col=self.col)
import pygame,random
#初始化
pygame.init()
W=800
H=600
ROW=30
COL=40
size=(W,H)
window = pygame.display.set_mode(size)
pygame.display.set_caption('贪吃蛇')
head = Point(row=int(ROW/2),col=int(COL/2))
snacks=[
Point(row=head.row,col=head.col+1),
Point(row=head.row,col=head.col+2),
Point(row=head.row,col=head.col+3)
]
#生成food
def gen_food():
while 1:
pos =Point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))
is_coll=False
#是否碰上
if head.col==pos.col and head.row==pos.row:
is_coll=True
for snack in snacks:
if snack.col==pos.col and snack.row == pos.row:
is_coll=True
break
if not is_coll:
break
return pos
#定义坐标
food = gen_food()
head_color=(228,0,0)
food_color= (255,225,0)
snack_color=(128,128,128)
direct='left'
#画
def rect(point,color):
cell_width=W/COL
cell_hight=H/ROW
left=point.col*cell_width
top =point.row*cell_hight
pygame.draw.rect(window,color,(left,top,cell_width,cell_hight),0)
#游戏循环
quit = True
clock = pygame.time.Clock()
while quit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit=False
if event.type ==pygame.KEYDOWN :
if event.key == pygame.K_LEFT:
if direct=='up' or direct=='down':
direct='left'
if event.key == pygame.K_RIGHT:
if direct == 'up' or direct == 'down':
direct = 'right'
if event.key == pygame.K_DOWN:
if direct == 'left' or direct == 'right':
direct = 'down'
if event.key == pygame.K_UP:
if direct == 'left' or direct == 'right':
direct = 'up'
#吃东西
eat=(head.row==food.row and head.col==food.col)
#处理身子
# 1.把原来的头插到snack头上
snacks.insert(0,head.copy())
#2.删掉snacks最后一个
if not eat:
snacks.pop()
if eat:
food = gen_food()
#移动
if direct=='left':
head.col-=1
elif direct=='right':
head.col+=1
elif direct=='up':
head.row-=1
elif direct=="down":
head.row+=1
#检测是否死了
dead=False
if head.row<0 or head.row>=ROW or head.col<0 or head.col>=COL:
dead=True
#撞自己
for snack in snacks:
if head.row==snack.row and snack.col==head.col:
dead=True
print('defefefd')
break
if dead==True:
print("死了")
quit=False
#渲染——画出来
pygame.draw.rect(window,(255,255,255),(0,0,W,H))#背景
#画蛇头
rect(head,head_color)
rect(food,food_color)
#画出蛇的身体
for snack in snacks:
rect(snack,snack_color)
# 让出控制权
pygame.display.flip()
#设置帧频
clock.tick(10)
运行结果: