一、玩法描述
貪吃蛇游戲是一款經(jīng)典的電子游戲,其核心玩法簡單但富有挑戰(zhàn)性。玩家控制一條不斷成長的蛇,在一個(gè)封閉的空間內(nèi)移動。游戲的目標(biāo)是盡可能長時(shí)間地生存下去,同時(shí)吃掉出現(xiàn)在屏幕上的食物來增加得分和蛇的長度。以下是貪吃蛇游戲的主要玩法和邏輯:
玩家通過鍵盤上的方向鍵或WASD鍵來改變蛇的移動方向,蛇在游戲區(qū)域內(nèi)自動前進(jìn),玩家需要及時(shí)調(diào)整方向以避免碰撞,游戲區(qū)域內(nèi)隨機(jī)生成食物。
當(dāng)蛇的頭部與食物的位置重合時(shí),蛇會吃掉食物,蛇的長度隨之增加,玩家的得分也會增加,每吃掉一個(gè)食物,蛇的長度就會增加一個(gè)單位,玩家的得分也相應(yīng)增加。游戲的難度隨著蛇的長度增加而增加,玩家需要避免蛇頭碰到自己的身體或游戲邊界,一旦發(fā)生碰撞,游戲就會結(jié)束。
游戲開始時(shí),蛇有一個(gè)初始長度,并在游戲區(qū)域內(nèi)的一個(gè)固定位置出現(xiàn)。游戲區(qū)域內(nèi)同時(shí)會隨機(jī)生成一個(gè)食物。蛇的身體由一系列相連的單位組成。蛇在移動時(shí),頭部向前移動一個(gè)單位距離,而每個(gè)身體單位都移動到前一個(gè)單位之前的位置,這樣就形成了蛇的連續(xù)移動效果。當(dāng)蛇吃掉一個(gè)食物后,游戲會在隨機(jī)位置生成一個(gè)新的食物,以便蛇繼續(xù)吃食并增長。如果蛇頭碰到自己的身體或游戲邊界,游戲結(jié)束。游戲結(jié)束時(shí),可以顯示玩家的最終得分,并提供重新開始游戲的選項(xiàng)。玩家的得分基于吃掉食物的數(shù)量。有些變種游戲可能會引入不同類型的食物,每種食物的得分可能不同。
二、游戲源代碼
需要通過pip安裝pygame ,如:pip install pygame
"""
Snake Eater
Made with PyGame
"""
import pygame, sys, time, random
# Difficulty settings
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
difficulty = 25
# Window size
frame_size_x = 720
frame_size_y = 480
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Game Over
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times', 20)
pygame.display.flip()
time.sleep(3)
pygame.quit()
sys.exit()
# Score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (frame_size_x/10, 15)
else:
score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)
game_window.blit(score_surface, score_rect)
# pygame.display.flip()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawning food on the screen
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# Game Over conditions
# Getting out of bounds
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:
game_over()
# Touching the snake body
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score(1, white, 'consolas', 20)
# Refresh game screen
pygame.display.update()
# Refresh rate
fps_controller.tick(difficulty)
三、游戲源代碼詳解
下面是對貪吃蛇游戲代碼的詳細(xì)分析,包括每個(gè)部分的功能和邏輯。
這部分代碼主要負(fù)責(zé)游戲的初始化設(shè)置,包括導(dǎo)入庫、設(shè)置難度、窗口大小、初始化Pygame、創(chuàng)建游戲窗口、定義顏色和創(chuàng)建FPS控制器。
# 導(dǎo)入必要的庫
import pygame, sys, time, random
# 設(shè)置游戲難度,影響蛇的移動速度
difficulty = 25
# 設(shè)置游戲窗口的大小
frame_size_x = 720
frame_size_y = 480
# 初始化pygame,并檢查是否有錯(cuò)誤發(fā)生
check_errors = pygame.init()
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# 設(shè)置游戲窗口的標(biāo)題,并創(chuàng)建游戲窗口
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# 定義游戲中使用的顏色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 創(chuàng)建一個(gè)FPS控制器,用于控制游戲的幀率
fps_controller = pygame.time.Clock()
這部分代碼初始化了游戲中的關(guān)鍵變量,包括蛇的位置和身體、食物的位置、蛇的移動方向和得分。
# 初始化蛇的位置和身體
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 隨機(jī)生成食物的位置,并設(shè)置食物生成標(biāo)志為True
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
# 設(shè)置初始移動方向?yàn)橛?,以及方向改變變?direction = 'RIGHT'
change_to = direction
# 初始化得分
score = 0
當(dāng)游戲結(jié)束(蛇撞到自己或邊界)時(shí),這個(gè)函數(shù)會被調(diào)用。它會顯示“YOU DIED”信息,展示最終得分,然后退出游戲。
def game_over():
# 設(shè)置游戲結(jié)束時(shí)的字體和大小
my_font = pygame.font.SysFont('times new roman', 90)
# 渲染游戲結(jié)束的文字
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)
# 填充背景色,顯示游戲結(jié)束的文字
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
# 顯示最終得分
show_score(0, red, 'times', 20)
pygame.display.flip()
# 等待3秒后退出游戲
time.sleep(3)
pygame.quit()
sys.exit()
當(dāng)游戲結(jié)束(蛇撞到自己或邊界)時(shí),這個(gè)函數(shù)會被調(diào)用。它會顯示“YOU DIED”信息,展示最終得分,然后退出游戲。
def show_score(choice, color, font, size):
# 設(shè)置得分的字體和大小
score_font = pygame.font.SysFont(font, size)
# 渲染得分的文字
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
# 根據(jù)choice參數(shù)決定得分顯示的位置
if choice == 1:
score_rect.midtop =(frame_size_x/10, 15)
else:
score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)
# 將得分的文字顯示在游戲窗口上
game_window.blit(score_surface, score_rect)
這個(gè)循環(huán)是游戲的核心,負(fù)責(zé)處理玩家的輸入、更新游戲狀態(tài)、繪制游戲畫面和檢查游戲結(jié)束條件。通過不斷循環(huán),游戲能夠?qū)崟r(shí)響應(yīng)玩家的操作,同時(shí)保持流暢的游戲體驗(yàn)。
while True:
# 處理游戲中的事件,例如按鍵
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
# 根據(jù)按鍵改變蛇的移動方向
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# 按下ESC鍵退出游戲
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# 確保蛇不能立即反向移動
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# 根據(jù)蛇的移動方向更新蛇頭的位置
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# 蛇吃到食物后增長身體,并重新生成食物
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
# 繪制游戲的背景、蛇和食物
game_window.fill(black)
for pos in snake_body:
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 檢查游戲結(jié)束的條件
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10 or snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:
game_over()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
# 顯示得分并更新游戲窗口
show_score(1, white, 'consolas', 20)
pygame.display.update()
# 控制游戲的幀率
fps_controller.tick(difficulty)
以上代碼就能開發(fā)一個(gè)簡單的貪吃蛇游戲了文章來源:http://www.zghlxwxcb.cn/news/detail-843533.html
本文由 曲速引擎(Warp Drive)個(gè)人博客https://www.exp-9.com/
曲速引擎(Warp Drive)CSDN技術(shù)博客https://blog.csdn.net/siberiaWarpDrive曲速引擎 Warp Drive 微信公眾號聯(lián)合創(chuàng)作,更多有趣的技術(shù)文章請關(guān)注個(gè)人博客,轉(zhuǎn)載請說明出處謝謝。文章來源地址http://www.zghlxwxcb.cn/news/detail-843533.html
到了這里,關(guān)于Python 游戲開發(fā) 如何寫一款貪吃蛇游戲詳解 - 曲速引擎(Warp Drive )的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!