news 2026/4/23 10:25:49

贪吃蛇(python版)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
贪吃蛇(python版)

安装依赖

pipinstallpygame

完整代码

importpygameimportrandomimportsys# 初始化pygamepygame.init()# 游戏配置WINDOW_WIDTH=800WINDOW_HEIGHT=600CELL_SIZE=20CELL_NUMBER_X=WINDOW_WIDTH//CELL_SIZE CELL_NUMBER_Y=WINDOW_HEIGHT//CELL_SIZE# 颜色定义BLACK=(0,0,0)WHITE=(255,255,255)GREEN=(0,255,0)DARK_GREEN=(0,200,0)RED=(255,0,0)BLUE=(0,0,255)GRAY=(40,40,40)GRASS_COLOR=(167,209,61)TEXT_COLOR=(255,255,255)# 设置游戏窗口screen=pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))pygame.display.set_caption('贪吃蛇游戏')clock=pygame.time.Clock()# 字体设置font=pygame.font.SysFont('arial',25)big_font=pygame.font.SysFont('arial',50)classSnake:def__init__(self):# 初始位置(身体由多个方块组成)self.body=[pygame.Vector2(5,10),pygame.Vector2(4,10),pygame.Vector2(3,10)]self.direction=pygame.Vector2(1,0)# 初始向右移动self.new_block=Falsedefdraw_snake(self):"""绘制蛇"""forindex,blockinenumerate(self.body):x_pos=int(block.x*CELL_SIZE)y_pos=int(block.y*CELL_SIZE)block_rect=pygame.Rect(x_pos,y_pos,CELL_SIZE,CELL_SIZE)# 蛇头用深绿色,身体用浅绿色ifindex==0:pygame.draw.rect(screen,DARK_GREEN,block_rect)else:pygame.draw.rect(screen,GREEN,block_rect)defmove_snake(self):"""移动蛇"""ifself.new_block:body_copy=self.body[:]body_copy.insert(0,body_copy[0]+self.direction)self.body=body_copy[:]self.new_block=Falseelse:body_copy=self.body[:-1]body_copy.insert(0,body_copy[0]+self.direction)self.body=body_copy[:]defadd_block(self):"""增加蛇的长度"""self.new_block=Truedefcheck_collision(self):"""检查碰撞(撞墙或撞自己)"""# 检查是否撞墙ifnot0<=self.body[0].x<CELL_NUMBER_Xornot0<=self.body[0].y<CELL_NUMBER_Y:returnTrue# 检查是否撞到自己forblockinself.body[1:]:ifblock==self.body[0]:returnTruereturnFalseclassFood:def__init__(self):self.randomize()defdraw_food(self):"""绘制食物"""food_rect=pygame.Rect(int(self.pos.x*CELL_SIZE),int(self.pos.y*CELL_SIZE),CELL_SIZE,CELL_SIZE)pygame.draw.rect(screen,RED,food_rect)defrandomize(self):"""随机生成食物位置"""self.x=random.randint(0,CELL_NUMBER_X-1)self.y=random.randint(0,CELL_NUMBER_Y-1)self.pos=pygame.Vector2(self.x,self.y)classGame:def__init__(self):self.snake=Snake()self.food=Food()self.score=0self.game_over=Falsedefupdate(self):"""更新游戏状态"""ifnotself.game_over:self.snake.move_snake()self.check_collision()self.check_fail()defdraw_elements(self):"""绘制所有游戏元素"""self.food.draw_food()self.snake.draw_snake()self.draw_score()ifself.game_over:self.draw_game_over()defcheck_collision(self):"""检查蛇是否吃到食物"""ifself.food.pos==self.snake.body[0]:self.food.randomize()self.snake.add_block()self.score+=1# 确保食物不会生成在蛇身上forblockinself.snake.body[1:]:ifblock==self.food.pos:self.food.randomize()defcheck_fail(self):"""检查游戏是否失败"""ifself.snake.check_collision():self.game_over=Truedefdraw_score(self):"""绘制分数"""score_text=str(self.score)score_surface=font.render(score_text,True,TEXT_COLOR)score_x=int(WINDOW_WIDTH-60)score_y=int(WINDOW_HEIGHT-40)score_rect=score_surface.get_rect(center=(score_x,score_y))screen.blit(score_surface,score_rect)defdraw_game_over(self):"""绘制游戏结束界面"""# 半透明遮罩overlay=pygame.Surface((WINDOW_WIDTH,WINDOW_HEIGHT))overlay.set_alpha(150)overlay.fill((0,0,0))screen.blit(overlay,(0,0))game_over_surface=big_font.render('GAME OVER',True,WHITE)game_over_rect=game_over_surface.get_rect(center=(WINDOW_WIDTH//2,WINDOW_HEIGHT//2-50))screen.blit(game_over_surface,game_over_rect)restart_text=font.render('Press R to Restart or Q to Quit',True,WHITE)restart_rect=restart_text.get_rect(center=(WINDOW_WIDTH//2,WINDOW_HEIGHT//2+20))screen.blit(restart_text,restart_rect)defreset(self):"""重置游戏"""self.snake=Snake()self.food=Food()self.score=0self.game_over=Falsedefmain():game=Game()# 自定义事件,控制蛇的移动速度SCREEN_UPDATE=pygame.USEREVENT pygame.time.set_timer(SCREEN_UPDATE,150)# 每150毫秒更新一次whileTrue:foreventinpygame.event.get():ifevent.type==pygame.QUIT:pygame.quit()sys.exit()ifevent.type==SCREEN_UPDATEandnotgame.game_over:game.update()ifevent.type==pygame.KEYDOWN:ifnotgame.game_over:# 控制蛇的方向(不能直接反向)ifevent.key==pygame.K_UPandgame.snake.direction.y!=1:game.snake.direction=pygame.Vector2(0,-1)ifevent.key==pygame.K_DOWNandgame.snake.direction.y!=-1:game.snake.direction=pygame.Vector2(0,1)ifevent.key==pygame.K_RIGHTandgame.snake.direction.x!=-1:game.snake.direction=pygame.Vector2(1,0)ifevent.key==pygame.K_LEFTandgame.snake.direction.x!=1:game.snake.direction=pygame.Vector2(-1,0)else:# 游戏结束时可以重新开始或退出ifevent.key==pygame.K_r:game.reset()ifevent.key==pygame.K_q:pygame.quit()sys.exit()screen.fill(GRAY)game.draw_elements()pygame.display.update()clock.tick(60)if__name__=='__main__':main()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 10:25:23

Blender MMD插件完全指南:打通二次元3D动画制作流程

Blender MMD插件完全指南&#xff1a;打通二次元3D动画制作流程 【免费下载链接】blender_mmd_tools MMD Tools is a blender addon for importing/exporting Models and Motions of MikuMikuDance. 项目地址: https://gitcode.com/gh_mirrors/bl/blender_mmd_tools MMD…

作者头像 李华
网站建设 2026/4/23 10:24:21

如何快速掌握华为设备Bootloader解锁:PotatoNV新手完整教程

如何快速掌握华为设备Bootloader解锁&#xff1a;PotatoNV新手完整教程 【免费下载链接】PotatoNV Unlock bootloader of Huawei devices on Kirin 960/95x/65x/620 项目地址: https://gitcode.com/gh_mirrors/po/PotatoNV 还在为华为设备系统限制而烦恼吗&#xff1f;想…

作者头像 李华
网站建设 2026/4/23 10:23:54

终极指南:如何快速免费解锁网易云音乐NCM格式限制

终极指南&#xff1a;如何快速免费解锁网易云音乐NCM格式限制 【免费下载链接】ncmdump 项目地址: https://gitcode.com/gh_mirrors/ncmd/ncmdump 你是否曾经遇到过这样的情况&#xff1a;在网易云音乐精心收藏的歌曲&#xff0c;却无法在车载音响、专业播放器或家庭音…

作者头像 李华