91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用pygame模塊編寫貪吃蛇的實例講解

發布時間:2020-08-27 16:47:50 來源:腳本之家 閱讀:182 作者:ykersimple 欄目:開發技術

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模塊編寫貪吃蛇的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

仪陇县| 沙河市| 云龙县| 淮南市| 晴隆县| 宾阳县| 西乌珠穆沁旗| 峨山| 同德县| 罗平县| 神农架林区| 南岸区| 蛟河市| 方山县| 同德县| 日照市| 东丽区| 北碚区| 灵丘县| 镇康县| 宿松县| 荔浦县| 榆林市| 丽水市| 贵港市| 南华县| 兰坪| 根河市| 安庆市| 永顺县| 尼勒克县| 辽宁省| 朝阳县| 余姚市| 桐城市| 潢川县| 响水县| 浑源县| 周至县| 长岭县| 永安市|