python贪吃蛇
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 import random pygame.init() width=800 height=600 ROW=30 COL=40 size=(width,height) window=pygame.display.set_mode(size) pygame.display.set_caption(‘mlhj‘) head=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1)) food=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1)) quit=True clock =pygame.time.Clock() back_color=(255,255,255) head_color=(255,0,0) snake_color=(128,128,128) food_color=(0,128,128) snakes=[] def rect(point,color): cell_width=width/COL cell_height=height/ROW left=point.col*(cell_width) top=point.row*(cell_height) pygame.draw.rect(window, color, (left, top, cell_width, cell_height)) pass dir=‘left‘ while quit: for event in pygame.event.get(): print(event) if event.type==pygame.QUIT: quit = False elif event.type==pygame.KEYDOWN: if event.key==273: if dir==‘left‘ or dir==‘right‘: dir=‘up‘ elif event.key==274: if dir == ‘left‘ or dir == ‘right‘: dir=‘down‘ elif event.key == 275: if dir == ‘up‘ or dir == ‘down‘: dir = ‘right‘ elif event.key == 276: if dir == ‘up‘ or dir == ‘down‘: dir = ‘left‘ eat = (head.row==food.row and head.col==food.col) snakes.insert(0,point.copy(head)) if not eat: #如果没吃到,移动的时候就把尾巴给‘扔了’,如果迟到了食物,则会增加一节,这一节刚好就是需要pop的那一个位置 snakes.pop() if eat: food = point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1)) #碰到边界死亡 if head.col>40 or head.row<0 or head.row>30or head.col<0: quit=False #碰到自己的身体死亡 for snake in snakes: if snake.row==head.row and snake.col==head.col: quit=False if dir==‘left‘: head.col-=1 elif dir==‘right‘: head.col+=1 elif dir==‘up‘: head.row-=1 elif dir == ‘down‘: head.row += 1 #渲染,将舌头蛇身食物等在界面上画出来 pygame.display.flip() pygame.draw.rect(window,back_color,(0,0,width,height)) rect(head,head_color) rect(food,food_color) for snake in snakes: rect(snake,snake_color) #设置帧频 clock.tick(10)
相关推荐
柠檬班 2020-01-06
zhaochen00 2020-08-20
tangjikede 2020-05-06
yawei 2020-01-04
tengyuan 2019-11-16
坚持是一种品质 2019-11-09
Mexican 2011-08-01
yanchuncheng 2019-05-15
lanseguhui 2019-06-30
人心 2019-06-30
bertZuo 2019-06-29
hushhw 2015-11-23
我的电子世界 2015-08-24
chenjh 2019-06-26
yaoliuwei 2014-03-06
Abudula 2012-07-05
lzn 2011-07-31
PHPer达人馆 2019-04-29