1、以下是 Python 实现的贪吃蛇小游戏代码:pythonimport pygameimport random#初始化 Pygamepygame.init()#设置游戏窗口大小和标题screen_width=480screen_height=480game_display=pygame.display.set_mode(screen_width,screen_height)pygame.display.set_caption(贪吃蛇游戏)#定义颜色white=(255,255,255)black=(0,0,0)red=(255,0,0)green=(0,255,0)#定义蛇的初始位置和尺寸sn
2、ake_block_size=20snake_speed=10initial_snake_pos=x:screen_width/2,y:screen_height/2snake_list=initial_snake_pos#定义食物的尺寸和位置food_block_size=20food_pos=x:round(random.randrange(0,screen_width-food_block_size)/20.0)*20.0,y:round(random.randrange(0,screen_height-food_block_size)/20.0)*20.0#定义分数、字体和大小scor
3、e=0font_style=pygame.font.SysFont(None,30)#刷新分数def refresh_score(score):score_text=font_style.render(Score:+str(score),True,black)game_display.blit(score_text,0,0)#绘制蛇def draw_snake(snake_block_size,snake_list):for pos in snake_list:pygame.draw.rect(game_display,green,posx,posy,snake_block_size)#显示消
4、息def message(msg,color):message_text=font_style.render(msg,True,color)game_display.blit(message_text,screen_width/6,screen_height/3)#主函数循环def game_loop():game_over=Falsegame_close=False#设置蛇头的初始移动方向x_change=0y_change=0#处理事件while not game_over:while game_close:game_display.fill(white)message(You lost!
5、Press Q-Quit or C-Play Again,red)refresh_score(score)pygame.display.update()#处理重新开始和退出事件for event in pygame.event.get():if event.type=pygame.KEYDOWN:if event.key=pygame.K_q:game_over=Truegame_close=Falseelif event.key=pygame.K_c:game_loop()#处理按键事件for event in pygame.event.get():if event.type=pygame.
6、QUIT:game_over=Trueif event.type=pygame.KEYDOWN:if event.key=pygame.K_LEFT:x_change=-snake_block_sizey_change=0elif event.key=pygame.K_RIGHT:x_change=snake_block_sizesnake_block_size,y_change=0elif event.key=pygame.K_UP:y_change=-snake_block_sizex_change=0elif event.key=pygame.K_DOWN:y_change=snake_
7、block_sizex_change=0#处理蛇的移动位置if snake_list-1x=screen_width or snake_list-1x=screen_height or snake_list-1y 0:game_close=Truesnake_list-1x+=x_changesnake_list-1y+=y_change#处理食物被吃掉的情况if snake_list-1x=food_posx and snake_list-1y=food_posy:score+=10food_pos=x:round(random.randrange(0,screen_width-food_b
8、lock_size)/20.0)*20.0,y:round(random.randrange(0,screen_height-food_block_size)/20.0)*20.0else:snake_list.pop(0)#处理蛇撞到自身的情况for pos in snake_list:-1:if pos=snake_list-1:game_close=True#刷新游戏窗口game_display.fill(white)draw_snake(snake_block_size,snake_list)pygame.draw.rect(game_display,red,food_posx,food_posy,food_block_size,food_block_size)refresh_score(score)pygame.display.update()#设置蛇移动的速度clock=pygame.time.Clock()clock.tick(snake_speed)pygame.quit()quit()game_loop()当您运行此代码时,将会启动一个贪吃蛇小游戏。在游戏中您可以通过方向键来控制贪吃蛇的移动方向,吃掉食物即可得到分数,蛇碰到墙壁或者碰到自己身体的时候游戏结束。