1 class point:
2 row=0
3 col=0
4 def __init__(self,row,col):
5 self.row=row
6 self.col=col
7 def copy(self):
8 return point(row=self.row,col=self.col)
9 #初始化框架
10 import pygame
11 import random
12 pygame.init()
13 width=800
14 height=600
15 ROW=30
16 COL=40
17 size=(width,height)
18 window=pygame.display.set_mode(size)
19 pygame.display.set_caption(‘mlhj‘)
20 head=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))
21 food=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))
22 quit=True
23 clock =pygame.time.Clock()
24 back_color=(255,255,255)
25 head_color=(255,0,0)
26 snake_color=(128,128,128)
27 food_color=(0,128,128)
28 snakes=[]
29 def rect(point,color):
30 cell_width=width/COL
31 cell_height=height/ROW
32 left=point.col*(cell_width)
33 top=point.row*(cell_height)
34 pygame.draw.rect(window, color, (left, top, cell_width, cell_height))
35 pass
36 dir=‘left‘
37 while quit:
38 for event in pygame.event.get():
39 print(event)
40 if event.type==pygame.QUIT:
41 quit = False
42 elif event.type==pygame.KEYDOWN:
43 if event.key==273:
44 if dir==‘left‘ or dir==‘right‘:
45 dir=‘up‘
46 elif event.key==274:
47 if dir == ‘left‘ or dir == ‘right‘:
48 dir=‘down‘
49 elif event.key == 275:
50 if dir == ‘up‘ or dir == ‘down‘:
51 dir = ‘right‘
52 elif event.key == 276:
53 if dir == ‘up‘ or dir == ‘down‘:
54 dir = ‘left‘
55 eat = (head.row==food.row and head.col==food.col)
56 snakes.insert(0,point.copy(head))
57 if not eat: #如果没吃到,移动的时候就把尾巴给‘扔了’,如果迟到了食物,则会增加一节,这一节刚好就是需要pop的那一个位置
58 snakes.pop()
59 if eat:
60 food = point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1))
61 #碰到边界死亡
62 if head.col>40 or head.row<0 or head.row>30or head.col<0:
63 quit=False
64 #碰到自己的身体死亡
65 for snake in snakes:
66 if snake.row==head.row and snake.col==head.col:
67 quit=False
68 if dir==‘left‘:
69 head.col-=1
70 elif dir==‘right‘:
71 head.col+=1
72 elif dir==‘up‘:
73 head.row-=1
74 elif dir == ‘down‘:
75 head.row += 1
76 #渲染,将舌头蛇身食物等在界面上画出来
77 pygame.display.flip()
78 pygame.draw.rect(window,back_color,(0,0,width,height))
79 rect(head,head_color)
80 rect(food,food_color)
81 for snake in snakes:
82 rect(snake,snake_color)
83
84
85
86 #设置帧频
87 clock.tick(10)
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
python贪吃蛇