使用pygame模块编写贪吃蛇的实例讲解


Posted in Python onFebruary 05, 2018

python ### 刚学了python不久,发现了一个好玩的库pygame

使用pygame模块 利用面向对象的思想编写贪吃蛇,主要用到pygame.sprite:

游戏主类

import pygame,sys
from snake_sprite import Game_sprite,Snake,Food
SCREEN_RECT=pygame.Rect(0,0,828,600)

IMG_URL="./image/bg.jpg"
#主类
class Snakegame(object):
 def __init__(self):
  self.screen=pygame.display.set_mode(SCREEN_RECT.size)
  self.clock=pygame.time.Clock()
  self.__create_sprites()

 def __create_sprites(self):
  bg=Game_sprite(IMG_URL)
  self.snake=Snake()
  for pos in self.snake.snake_point:
   self.screen.blit(self.snake.image,pos)
  food=Food()
  self.bg_group=pygame.sprite.Group(bg)
  self.snake_group=pygame.sprite.Group(self.snake)
  self.food_group = pygame.sprite.Group(food)
 def start_game(self):
  while True:
   #1.时钟设置
   self.clock.tick(30)
   #2.事件监听
   self.__event_handler()
   #3.碰撞检测
   self.__check_collide()
   #4.精灵更新
   self.__update_sprites()
   #5.屏幕更新
   pygame.display.update()
 def __event_handler(self):
  for event in pygame.event.get():
   if event.type==pygame.QUIT:
    Snakegame.__game_over()
   elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT and \
     self.snake.direction !='L':
    self.snake.speedy = 0
    self.snake.speedx = 1
    self.snake.direction = 'R'
   elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT and \
     self.snake.direction !='R':
    self.snake.speedy = 0
    self.snake.speedx = -1
    self.snake.direction = 'L'
   elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP and \
     self.snake.direction !='D':
    self.snake.speedx = 0
    self.snake.speedy = -1
    self.snake.direction = 'U'
   elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and \
     self.snake.direction !='U':
    self.snake.speedx=0
    self.snake.speedy=1
    self.snake.direction='D'
 def __check_collide(self):
  pass
 def __update_sprites(self):
  self.bg_group.update()
  self.bg_group.draw(self.screen)
  self.snake_group.update()
  self.snake_group.draw(self.screen)
  self.food_group.update()
  self.food_group.draw(self.screen)
 @staticmethod
 def __game_over():
  pygame.quit()
  exit()

#游戏启动
if __name__ == '__main__':
 snake=Snakegame()
 snake.start_game()

工具类

import pygame
import random
SNAKE_IMG="./image/snake.png"
FOOD_IMG="./image/food.jpg"
class Game_sprite(pygame.sprite.Sprite):
 def __init__(self,img_name,speedx=1,speedy=0):
  #调用父类的初始化方法
  super(Game_sprite, self).__init__()
  #属性
  self.image=pygame.image.load(img_name)
  self.rect=self.image.get_rect()
  self.speedx=speedx
  self.speedy=speedy
 def update(self):
  pass
#蛇实物
class Snake(Game_sprite):
 def __init__(self,direction='R',snakelist=[[40,40],[80,40]]):
  self.direction=direction
  self.snake_point=snakelist
  super().__init__(SNAKE_IMG)
  self.rect.x=self.snake_point[1][0]
  self.rect.y=self.snake_point[1][1]
 def update(self):
  self.rect.x += self.speedx
  self.rect.y += self.speedy
class Food(Game_sprite):
 def __init__(self):
  super(Food, self).__init__(FOOD_IMG)
  self.rect.x = random.randint(50, 828)
  self.rect.y = random.randint(38, 600)
 def update(self):
  pass

关于这次demo

我发现自己并没有弄懂pygame的具体画面更新机制,以及精灵的控制,对于贪吃蛇头部及身体的画面更新并没有做出来,还有对身体和头的数据结构如何构建 并不是很了解。毕竟第一次,希望有大佬看到这篇博客能够指点下。

附上函数式编程的代码

import pygame
import time
import random
x = pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')
gameDisplay.fill(white)
pygame.display.update()
block_size = 20
applethickness = 30
FPS = 10
icon = pygame.image.load('appleimage.jpg')
pygame.display.set_icon(icon)
img = pygame.image.load('snakeimage.jpg')
appleimage = pygame.image.load('appleimage.jpg')
clock = pygame.time.Clock()
smallfont = pygame.font.SysFont(None,30)
midfont = pygame.font.SysFont(None,50)
largefont = pygame.font.SysFont("comicsansms",80)
direction = "right"
def pause():
 paused = True
 message_to_screen("暂停",black,-100,"large")
 message_to_screen("空格暂停Q退出",black, 30)
 pygame.display.update()
 while paused:
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    pygame.quit()
    quit()
   if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
     paused = False
    elif event.key == pygame.K_q:
     pygame.quit()
     quit()
  #gameDisplay.fill(white)
 clock.tick(5)

def score(score):
 text1 = smallfont.render("Score : " + str(score), True, black)
 gameDisplay.blit(text1,(0,0))
def randApplegen():
 randAppleX = round(random.randrange(0,display_width-applethickness))#/10.0)*10.0
 randAppleY = round(random.randrange(0,display_height-applethickness))#/10.0)*10.0
 return randAppleX, randAppleY

def intro():
 intro = True
 message_to_screen("按c开始游戏",red,150)
 pygame.display.update()
 while intro:
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    pygame.quit()
    quit()
   if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_c:
     intro = False
    if event.key == pygame.K_q:
     pygame.quit()
     quit()
  clock.tick(15)
def snake(snakelist):
 for xny in snakelist[:-1]:
  pygame.draw.rect(gameDisplay,green,[xny[0],xny[1],block_size,block_size])
 if(direction == "right"):
  head = pygame.transform.rotate(img,270)
 elif(direction == "left"):
  head = pygame.transform.rotate(img,90)
 elif(direction == "up"):
  head = img
 elif(direction == "down"):
  head = pygame.transform.rotate(img,180)
 gameDisplay.blit(head,(snakelist[-1][0],snakelist[-1][1]))
def text_objects(text,color,size):
 if(size == "small"):
  textsurface = smallfont.render(text,True,color)
 elif(size == "middle"):
  textsurface = midfont.render(text,True,color)
 elif(size == "large"):
  textsurface = largefont.render(text,True,color)
 return textsurface, textsurface.get_rect()
def message_to_screen(msg,color,y_displace=0,size="small"):
 textsurf, textsurf_rect = text_objects(msg,color,size)
 textsurf_rect.center = (display_width/2), (display_height/2) + y_displace
 gameDisplay.blit(textsurf,textsurf_rect)

def gameLoop():
 global direction
 direction = "right"
 gameExit = False
 gameOver = False
 lead_x = display_width/2
 lead_y = display_height/2
 lead_x_change = 10
 lead_y_change = 0
 randAppleX, randAppleY = randApplegen()
 snakelist = []
 snakelength = 1
 while not gameExit:
  if gameOver == True:
   message_to_screen("Game Over",red,-50,"large")
   message_to_screen("Press C to play again or Q to quit the game",black,50,"small")
   pygame.display.update()
  while gameOver == True:
   #gameDisplay.fill(white)
   for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
     if event.key == pygame.K_q:
      gameExit = True
      gameOver = False
     if event.key == pygame.K_c:
      gameLoop()
      pygame.quit()
      quit()
    if event.type == pygame.QUIT:
     gameExit = True 
     gameOver = False
     # pygame.quit()
     # quit()
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    gameExit = True 
   if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT and direction != "right":
     direction = "left"
     lead_x_change = -block_size
     lead_y_change = 0
    elif event.key == pygame.K_RIGHT and direction != "left":
     direction = "right"
     lead_x_change = block_size
     lead_y_change = 0
    elif event.key == pygame.K_UP and direction != "down":
     direction = "up"
     lead_y_change = -block_size
     lead_x_change = 0
    elif event.key == pygame.K_DOWN and direction != "up":
     direction = "down"
     lead_y_change = block_size
     lead_x_change = 0
    elif event.key == pygame.K_SPACE:
     pause()
  if lead_x + block_size/2 >= display_width or lead_x < 0 or lead_y + block_size/2 >= display_height or lead_y < 0:
   gameOver = True
  lead_x += lead_x_change
  lead_y += lead_y_change
  gameDisplay.fill(white)
  gameDisplay.blit(appleimage,(randAppleX,randAppleY))
  #pygame.draw.rect(gameDisplay,red,[350,350,100,10])
  # gameDisplay.fill(red, rect=[200,200,50,50])  #good method
  snakehead = []
  snakehead.append(lead_x)
  snakehead.append(lead_y)
  snakelist.append(snakehead)
  if len(snakelist) > snakelength:
   del snakelist[0]
  for each in snakelist[:-1]:
   if each == snakehead:
    gameOver = True
  snake(snakelist)
  score(snakelength-1)
  pygame.display.update()
  if lead_x >= randAppleX and lead_x <= randAppleX + applethickness or lead_x + block_size >= randAppleX and lead_x + block_size <= randAppleX + applethickness:
   if lead_y >= randAppleY and lead_y <= randAppleY + applethickness or lead_y + block_size >= randAppleY and lead_y + block_size <= randAppleY + applethickness:
    randAppleX, randAppleY = randApplegen()
    snakelength += 1;    
  clock.tick(FPS)
intro()
gameLoop()

pygame.quit()
quit()

以上这篇使用pygame模块编写贪吃蛇的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
日常整理python执行系统命令的常见方法(全)
Oct 22 Python
Python分治法定义与应用实例详解
Jul 28 Python
Python编程实现从字典中提取子集的方法分析
Feb 09 Python
对python中xlsx,csv以及json文件的相互转化方法详解
Dec 25 Python
利用Python对文件夹下图片数据进行批量改名的代码实例
Feb 21 Python
python实现扫描局域网指定网段ip的方法
Apr 16 Python
对pyqt5多线程正确的开启姿势详解
Jun 14 Python
python中时间、日期、时间戳的转换的实现方法
Jul 06 Python
详解python 中in 的 用法
Dec 12 Python
使用Python webdriver图书馆抢座自动预约的正确方法
Mar 04 Python
pytorch中[..., 0]的用法说明
May 20 Python
使用python绘制横竖条形图
Apr 21 Python
Python安装模块的常见问题及解决方法
Feb 05 #Python
Python实现的用户登录系统功能示例
Feb 05 #Python
python中numpy的矩阵、多维数组的用法
Feb 05 #Python
NumPy 如何生成多维数组的方法
Feb 05 #Python
python生成器,可迭代对象,迭代器区别和联系
Feb 04 #Python
python实现mysql的读写分离及负载均衡
Feb 04 #Python
python负载均衡的简单实现方法
Feb 04 #Python
You might like
c#中的实现php中的preg_replace
2009/12/21 PHP
PHP管理依赖(dependency)关系工具 Composer 安装与使用
2014/08/18 PHP
[原创]PHP简单开启curl的方法(测试可行)
2016/01/11 PHP
微信小程序发送订阅消息的方法(php 为例)
2019/10/30 PHP
一个js写的日历(代码部分网摘)
2009/09/20 Javascript
JavaScript Event学习补遗 addEventSimple
2010/02/11 Javascript
js 手机号码合法性验证代码集合
2012/09/29 Javascript
使用jQuery实现图片遮罩半透明坠落遮挡
2015/03/16 Javascript
js计算文本框输入的字符数
2015/10/23 Javascript
jQuery实现为控件添加水印文字效果(附源码)
2015/12/02 Javascript
基于zepto的移动端轻量级日期插件--date_picker
2016/03/04 Javascript
jQuery模仿阿里云购买服务器选择购买时间长度的代码
2016/04/29 Javascript
微信小程序 登录实例详解
2017/01/16 Javascript
Vue学习笔记进阶篇之单元素过度
2017/07/19 Javascript
nodejs中express入门和基础知识点学习
2018/09/13 NodeJs
js根据json数据中的某一个属性来给数据分组的方法
2018/10/08 Javascript
vue-cli3 项目从搭建优化到docker部署的方法
2019/01/28 Javascript
vue实现登录拦截
2020/06/29 Javascript
Java中重定向输出流实现用文件记录程序日志
2015/06/12 Python
python选择排序算法实例总结
2015/07/01 Python
Python实现爬取逐浪小说的方法
2015/07/07 Python
多版本Python共存的配置方法
2017/05/22 Python
详解Python函数可变参数定义及其参数传递方式
2017/08/02 Python
python实现三维拟合的方法
2018/12/29 Python
浅谈python函数调用返回两个或多个变量的方法
2019/01/23 Python
Python分布式进程中你会遇到的问题解析
2019/05/28 Python
python3用PIL把图片转换为RGB图片的实例
2019/07/04 Python
python nohup 实现远程运行不宕机操作
2020/04/16 Python
Python爬虫之Selenium设置元素等待的方法
2020/12/04 Python
Skyscanner阿联酋:全球领先的旅游搜索平台
2017/11/25 全球购物
宝拉珍选官方旗舰店:2%水杨酸精华液,收缩毛孔粗大和祛痘
2018/07/01 全球购物
美国眼镜网站:LensCrafters
2020/01/19 全球购物
教师反腐倡廉演讲稿
2014/09/03 职场文书
2014乡镇干部纪律作风整顿思想汇报
2014/09/13 职场文书
网站文案策划岗位职责
2015/04/14 职场文书
2021年pycharm的最新安装教程及基本使用图文详解
2021/04/03 Python