四时宝库

程序员的知识宝库

一个简单的贪吃蛇游戏代码Python


import pygame

import random

# 初始化 pygame

pygame.init()

# 设置游戏窗口大小

window_width = 800

window_height = 600

window = pygame.display.set_mode((window_width, window_height))

pygame.display.set_caption("贪吃蛇游戏")

# 定义颜色

white = (255, 255, 255)

black = (0, 0, 0)

red = (255, 0, 0)

green = (0, 255, 0)

# 蛇的方块大小和初始速度

block_size = 20

snake_speed = 15

# 定义字体

font_style = pygame.font.SysFont(None, 50)

def message(msg, color):

mesg = font_style.render(msg, True, color)

window.blit(mesg, [window_width / 6, window_height / 3])

# 绘制蛇

def draw_snake(snake_block, snake_list):

for x in snake_list:

pygame.draw.rect(window, green, [x[0], x[1], snake_block, snake_block])

# 游戏主循环

def game_loop():

game_over = False

game_close = False


x1 = window_width / 2

y1 = window_height / 2


x1_change = 0

y1_change = 0


snake_list = []

length_of_snake = 1


foodx = round(random.randint(0, (window_width - block_size) / block_size)) * block_size

foody = round(random.randint(0, (window_height - block_size) / block_size)) * block_size


while not game_over:


while game_close:

window.fill(white)

message("游戏结束!按Q退出或C重新开始", 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:

game_loop()


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 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:

game_close = True


x1 += x1_change

y1 += y1_change

window.fill(white)

pygame.draw.rect(window, 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.randint(0, (window_width - block_size) / block_size)) * block_size

foody = round(random.randint(0, (window_height - block_size) / block_size)) * block_size

length_of_snake += 1


pygame.time.Clock().tick(snake_speed)


pygame.quit()

quit()


if __name__ == "__main__":

game_loop()

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接