简单的贪吃蛇小游戏的 Python 代码:文章来源地址https://www.toymoban.com/news/detail-721515.html
import pygame
import random
# 初始化
pygame.init()
# 游戏窗口大小
width = 800
height = 600
# 设置游戏窗口
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])
# 游戏循环
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
# 游戏循环
while not game_over:
# 游戏结束
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()
# 运行游戏
gameLoop()
文章来源:https://www.toymoban.com/news/detail-721515.html
到了这里,关于简单的贪吃蛇小游戏的 Python 代码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!