您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“基于Pygame如何實現簡單的貪吃蛇游戲”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“基于Pygame如何實現簡單的貪吃蛇游戲”這篇文章吧。
import pygame, sys, random from pygame.locals import *
設置屏幕大小為400*400,mainClock = pygame.time.Clock()用來設置時間同步,不會根據計算機的運行來決定運行多少次, mainClock.tick(1) 一秒只會運行一次,設置了屏幕的底色為白色。
# 定義屏幕的寬高 WIDTH = 400 HEIGHT = 400 # 初始化屏幕 設置窗口標題 surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('貪吃蛇') pygame.init() mainClock = pygame.time.Clock() # 定義使用的顏色 BLACK = (0, 0, 0) GREEN = (0, 255, 0) WHITE = (255, 255, 255) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() surface.fill(WHITE) pygame.display.update() mainClock.tick(1)
這里設置了貪吃蛇的長度和起始位置,和食物和蛇的寬度,這里必須設置為可以被食物和蛇的寬度整除的數,這樣才能保證蛇能到任意的位置
# 設置蛇的初始長度 snakeWidth = 4 # 設置蛇的起始位置為(40,40) snakeX = 40 snakeY = 40 # 食物和蛇的寬度設置為8 FOODSNAKEWIDTH = 8 # 定義四個方向 moveLeft = False moveRight = False moveUp = False moveDown = False # 定義初始的方向 moveRight = True def getSnake(): # 設置蛇的初始長度為4,并設置蛇的初始位置為(40,40) # 因為貪吃蛇會拐彎,所以將蛇設置為一個列表 snake = [] for i in range(snakeWidth): snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) return snake # 貪吃蛇 snake = getSnake()
surface.fill(WHITE) for s in snake: pygame.draw.rect(surface, BLACK, s)
這里將蛇列表最后一位移除,然后將第一位的位置根據方向加減坐標
snake.pop() newTop = copy.deepcopy(snake[0]) # 改變蛇的位置 if moveRight: newTop.left += FOODSNAKEWIDTH if moveLeft: newTop.left -= FOODSNAKEWIDTH if moveUp: newTop.top -= FOODSNAKEWIDTH if moveDown: newTop.top += FOODSNAKEWIDTH snake.insert(0, newTop)
這樣會有一個問題,如果超出屏幕呢,我們將超出屏幕,那么就會消失,我們只需要你移動第一個元素的時候,如果超出則將元素移動另一個位置。
# 改變蛇的位置 if moveRight: if newTop.right == WIDTH: newTop.left = 0 else: newTop.left += FOODSNAKEWIDTH if moveLeft: if newTop.left == 0: newTop.right == WIDTH else: newTop.left -= FOODSNAKEWIDTH if moveUp: if newTop.top == 0: newTop.bottom = HEIGHT else: newTop.top -= FOODSNAKEWIDTH if moveDown: if newTop.bottom == HEIGHT: newTop.top = 0 else: newTop.top += FOODSNAKEWIDTH
為了實現對應的功能,我們將方向變量改為一個變量,這樣我們方便修改方向
# 定義四個方向 # moveLeft moveRight moveUp moveDown # 定義初始的方向 snakeDirection = "moveRight" ---- 省略的代碼 ---- for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: if snakeDirection == "moveRight": snake.reverse() snakeDirection = "moveLeft" if event.key == K_RIGHT: if snakeDirection == "moveLeft": snake.reverse() snakeDirection = "moveRight" if event.key == K_UP: if snakeDirection == "moveDown": snake.reverse() snakeDirection = "moveUp" if event.key == K_DOWN: if snakeDirection == "moveUp": snake.reverse() snakeDirection = "moveDown"
為了方便看到效果,我將mainClock.tick(1) 設置為mainClock.tick(3)
這里用了很啰嗦的代碼,我自己也看不下去,有點含糊,這里為了簡單只設計了一個食物,遍歷屏幕上不是貪吃蛇的可以放食物的集合,然后隨機生成一個食物。
if len(foods) < foodnum: canFoodColl = [] # 獲取當前不是貪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'], f['y'], FOODSNAKEWIDTH, FOODSNAKEWIDTH))
這里用 colliderect判斷二者是否相撞,然后食物集合置空,不減去貪吃蛇集合的最后一個元素。
if len(foods) < foodnum: canFoodColl = [] # 獲取當前不是貪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) print(f['x']) print(f['y']) else: if newTop.colliderect(foods[0]): foods = [] eatFlg = True print('xxx')
import pygame, sys, random from pygame.locals import * import copy # 定義屏幕的寬高 WIDTH = 400 HEIGHT = 400 # 初始化屏幕 設置窗口標題 surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('貪吃蛇') pygame.init() mainClock = pygame.time.Clock() # 定義使用的顏色 BLACK = (0, 0, 0) GREEN = (0, 255, 0) WHITE = (255, 255, 255) # 設置蛇的初始長度 snakeWidth = 4 # 設置蛇的起始位置為(40,40) snakeX = 40 snakeY = 40 # 食物和蛇的寬度設置為8 FOODSNAKEWIDTH = 8 # 定義四個方向 # moveLeft moveRight moveUp moveDown # 定義初始的方向 snakeDirection = "moveRight" # 食物區間 foods = [] # 用去寬度處以對應的 大小,減去1 就是食物矩形起點可以存在的區間 #sizeNum = HEIGHT / FOODSNAKEWIDTH - 1 # 這里為了減少計算 sizeNum = 39 # 為了簡單我們只設置一個食物 foodnum = 1 def getSnake(): # 設置蛇的初始長度為4,并設置蛇的初始位置為(40,40) # 因為貪吃蛇會拐彎,所以將蛇設置為一個列表 snake = [] for i in range(snakeWidth): snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) return snake # 貪吃蛇 snake = getSnake() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: if snakeDirection == "moveRight": snake.reverse() snakeDirection = "moveLeft" if event.key == K_RIGHT: if snakeDirection == "moveLeft": snake.reverse() snakeDirection = "moveRight" if event.key == K_UP: if snakeDirection == "moveDown": snake.reverse() snakeDirection = "moveUp" if event.key == K_DOWN: if snakeDirection == "moveUp": snake.reverse() snakeDirection = "moveDown" surface.fill(WHITE) for s in snake: pygame.draw.rect(surface, BLACK, s) for f in foods: pygame.draw.rect(surface, GREEN, f) pygame.display.update() # 是否吃了食物 eatFlg = False newTop = copy.deepcopy(snake[0]) # 改變蛇的位置 if snakeDirection == "moveRight": if newTop.right == WIDTH: newTop.left = 0 else: newTop.left += FOODSNAKEWIDTH if snakeDirection == "moveLeft": if newTop.left == 0: newTop.right = WIDTH else: newTop.left -= FOODSNAKEWIDTH if snakeDirection == "moveUp": if newTop.top == 0: newTop.bottom = HEIGHT else: newTop.top -= FOODSNAKEWIDTH if snakeDirection == "moveDown": if newTop.bottom == HEIGHT: newTop.top = 0 else: newTop.top += FOODSNAKEWIDTH if len(foods) < foodnum: canFoodColl = [] # 獲取當前不是貪吃蛇的位置集合 for x in range(sizeNum): for y in range(sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top: foodExist = False break if foodExist: canFoodColl.append({'x': x, 'y': y}) f = canFoodColl[random.randint(0, len(canFoodColl))] foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) print(f['x']) print(f['y']) else: if newTop.colliderect(foods[0]): foods = [] eatFlg = True print('xxx') snake.insert(0, newTop) if not eatFlg: snake.pop() mainClock.tick(3)
以上是“基于Pygame如何實現簡單的貪吃蛇游戲”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。