簡單的貪吃蛇小游戲的 Python 代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-721515.html
import pygame
import random
# 初始化
pygame.init()
# 游戲窗口大小
width = 800
height = 600
# 設(shè)置游戲窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
# 顏色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 蛇的大小
block_size = 10
# 字體
font_style = pygame.font.SysFont(None, 30)
# 顯示消息
def message(msg, color):
message = font_style.render(msg, True, color)
screen.blit(message, [width / 6, height / 3])
# 繪制蛇
def draw_snake(block_size, snake_List):
for x in snake_List:
pygame.draw.rect(screen, green, [x[0], x[1], block_size, block_size])
# 游戲循環(huán)
def gameLoop():
game_over = False
game_close = False
# 蛇的初始位置
x1 = width / 2
y1 = height / 2
# 蛇的移動距離
x1_change = 0
y1_change = 0
# 初始長度
snake_List = []
Length_of_snake = 1
# 食物的位置
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
# 游戲循環(huán)
while not game_over:
# 游戲結(jié)束
while game_close == True:
screen.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
# 判斷按鍵
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
# 判斷按鍵
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 判斷蛇是否出界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 移動蛇
x1 += x1_change
y1 += y1_change
# 繪制食物
screen.fill(white)
pygame.draw.rect(screen, red, [foodx, foody, block_size, block_size])
# 蛇的長度
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 判斷蛇是否吃到食物
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# 繪制蛇
draw_snake(block_size, snake_List)
pygame.display.update()
# 判斷蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
Length_of_snake += 1
# 刷新屏幕
pygame.display.update()
# 退出游戲
pygame.quit()
quit()
# 運(yùn)行游戲
gameLoop()
文章來源:http://www.zghlxwxcb.cn/news/detail-721515.html
到了這里,關(guān)于簡單的貪吃蛇小游戲的 Python 代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!