侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PyGame贪吃蛇的实现代码示例

Python  /  管理员 发布于 5年前   178

最近帮人做了个贪吃蛇的游戏(交作业用),很简单,界面如下:

开始界面:

游戏中界面:

是不是很简单、朴素。(欢迎大家访问GitHub)

游戏是基于PyGame框架制作的,程序核心逻辑如下:

  • 游戏界面分辨率是640*480,蛇和食物都是由1个或多个20*20像素的正方形块儿(为了方便,下文用点表示20*20像素的正方形块儿)组成,这样共有32*24个点,使用pygame.draw.rect来绘制每一个点;
  • 初始化时蛇的长度是3,食物是1个点,蛇初始的移动的方向是右,用一个数组代表蛇,数组的每个元素是蛇每个点的坐标,因此数组的第一个坐标是蛇尾,最后一个坐标是蛇头;
  • 游戏开始后,根据蛇的当前移动方向,将蛇运动方向的前方的那个点append到蛇数组的末位,再把蛇尾去掉,蛇的坐标数组就相当于往前挪了一位;
  • 如果蛇吃到了食物,即蛇头的坐标等于食物的坐标,那么在第2点中蛇尾就不用去掉,就产生了蛇长度增加的效果;食物被吃掉后,随机在空的位置(不能与蛇的身体重合)再生成一个;
  • 通过PyGame的event监控按键,改变蛇的方向,例如当蛇向右时,下一次改变方向只能向上或者向下;
  • 当蛇撞上自身或墙壁,游戏结束,蛇头装上自身,那么蛇坐标数组里就有和舌头坐标重复的数据,撞上墙壁则是蛇头坐标超过了边界,都很好判断;
  • 其他细节:做了个开始的欢迎界面;食物的颜色随机生成;吃到实物的时候有声音提示等。

代码:

#!/usr/bin/env python # -*- coding:utf-8 -*- """ @version: v1.0 @author: Harp@contact: [email protected] @software: PyCharm @file: MySnake.py @time: 2018/1/15 0015 23:40 """import pygamefrom os import pathfrom sys import exitfrom time import sleepfrom random import choicefrom itertools import productfrom pygame.locals import QUIT, KEYDOWNdef direction_check(moving_direction, change_direction):  directions = [['up', 'down'], ['left', 'right']]  if moving_direction in directions[0] and change_direction in directions[1]:    return change_direction  elif moving_direction in directions[1] and change_direction in directions[0]:    return change_direction  return moving_directionclass Snake:  colors = list(product([0, 64, 128, 192, 255], repeat=3))[1:-1]  def __init__(self):    self.map = {(x, y): 0 for x in range(32) for y in range(24)}    self.body = [[100, 100], [120, 100], [140, 100]]    self.head = [140, 100]    self.food = []    self.food_color = []    self.moving_direction = 'right'    self.speed = 4    self.generate_food()    self.game_started = False  def check_game_status(self):    if self.body.count(self.head) > 1:      return True    if self.head[0] < 0 or self.head[0] > 620 or self.head[1] < 0 or self.head[1] > 460:      return True    return False  def move_head(self):    moves = {      'right': (20, 0),      'up': (0, -20),      'down': (0, 20),      'left': (-20, 0)    }    step = moves[self.moving_direction]    self.head[0] += step[0]    self.head[1] += step[1]  def generate_food(self):    self.speed = len(self.body) // 16 if len(self.body) // 16 > 4 else self.speed    for seg in self.body:      x, y = seg      self.map[x//20, y//20] = 1    empty_pos = [pos for pos in self.map.keys() if not self.map[pos]]    result = choice(empty_pos)    self.food_color = list(choice(self.colors))    self.food = [result[0]*20, result[1]*20]def main():  key_direction_dict = {    119: 'up', # W    115: 'down', # S    97: 'left', # A    100: 'right', # D    273: 'up', # UP    274: 'down', # DOWN    276: 'left', # LEFT    275: 'right', # RIGHT  }  fps_clock = pygame.time.Clock()  pygame.init()  pygame.mixer.init()  snake = Snake()  sound = False  if path.exists('eat.wav'):    sound_wav = pygame.mixer.Sound("eat.wav")    sound = True  title_font = pygame.font.SysFont('arial', 32)  welcome_words = title_font.render('Welcome to My Snake', True, (0, 0, 0), (255, 255, 255))  tips_font = pygame.font.SysFont('arial', 24)  start_game_words = tips_font.render('Click to Start Game', True, (0, 0, 0), (255, 255, 255))  close_game_words = tips_font.render('Press ESC to Close', True, (0, 0, 0), (255, 255, 255))  gameover_words = title_font.render('GAME OVER', True, (205, 92, 92), (255, 255, 255))  win_words = title_font.render('THE SNAKE IS LONG ENOUGH AND YOU WIN!', True, (0, 0, 205), (255, 255, 255))  screen = pygame.display.set_mode((640, 480), 0, 32)  pygame.display.set_caption('My Snake')  new_direction = snake.moving_direction  while 1:    for event in pygame.event.get():      if event.type == QUIT:        exit()      elif event.type == KEYDOWN:        if event.key == 27:          exit()        if snake.game_started and event.key in key_direction_dict:          direction = key_direction_dict[event.key]          new_direction = direction_check(snake.moving_direction, direction)      elif (not snake.game_started) and event.type == pygame.MOUSEBUTTONDOWN:        x, y = pygame.mouse.get_pos()        if 213 <= x <= 422 and 304 <= y <= 342:          snake.game_started = True    screen.fill((255, 255, 255))    if snake.game_started:      snake.moving_direction = new_direction # 在这里赋值,而不是在event事件的循环中赋值,避免按键太快      snake.move_head()      snake.body.append(snake.head[:])      if snake.head == snake.food:        if sound:          sound_wav.play()        snake.generate_food()      else:        snake.body.pop(0)      for seg in snake.body:        pygame.draw.rect(screen, [0, 0, 0], [seg[0], seg[1], 20, 20], 0)      pygame.draw.rect(screen, snake.food_color, [snake.food[0], snake.food[1], 20, 20], 0)      if snake.check_game_status():        screen.blit(gameover_words, (241, 310))        pygame.display.update()        snake = Snake()        new_direction = snake.moving_direction        sleep(3)      elif len(snake.body) == 512:        screen.blit(win_words, (33, 210))        pygame.display.update()        snake = Snake()        new_direction = snake.moving_direction        sleep(3)    else:      screen.blit(welcome_words, (188, 100))      screen.blit(start_game_words, (236, 310))      screen.blit(close_game_words, (233, 350))    pygame.display.update()    fps_clock.tick(snake.speed)if __name__ == '__main__':  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    pygame游戏之旅 创建游戏窗口界面
    下一条:
    pygame游戏之旅 添加icon和bgm音效的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客