使用pygame模块编写贪吃蛇的实例讲解-创新互联
python ### 刚学了python不久,发现了一个好玩的库pygame
创新互联主营阳信网站建设的网络公司,主营网站建设方案,APP应用开发,阳信h5小程序开发搭建,阳信网站营销推广欢迎阳信等地区企业咨询使用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()
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前题目:使用pygame模块编写贪吃蛇的实例讲解-创新互联
文章起源:http://azwzsj.com/article/hoegj.html