用pygame做一个简单的python小游戏—贪吃蛇
贪吃蛇游戏链接:
c++贪吃蛇:https://blog.****.net/weixin_46791942/article/details/106850986
python贪吃蛇:https://blog.****.net/weixin_46791942/article/details/110383746
正文开始
下载pygame模块
pip install pygame
编写的是最简单的贪吃蛇游戏(实现最基本的功能)
效果图:

附上代码:
import pygame, sys, time, random
color_red = pygame.Color(255, 0, 0)
color_white = pygame.Color(255, 255, 255)
color_green = pygame.Color(0, 255, 0)
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill(color_white)
pygame.display.set_caption("贪吃蛇小游戏")
arr = [([0] * 41) for i in range(61)]
x = 10
y = 10
foodx = random.randint(1, 60)
foody = random.randint(1, 40)
arr[foodx][foody] = -1
snake_lon = 3
way = 1
while True:
screen.fill(color_white)
time.sleep(0.1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if (event.key == pygame.K_RIGHT) and (way != 2):
way = 1
if (event.key == pygame.K_LEFT) and (way != 1):
way = 2
if (event.key == pygame.K_UP) and (way != 4):
way = 3
if (event.key == pygame.K_DOWN) and (way != 3):
way = 4
if way == 1:
x += 1
if way == 2:
x -= 1
if way == 3:
y -= 1
if way == 4:
y += 1
if (x > 60) or (y > 40) or (x < 1) or (y < 1) or (arr[x][y] > 0):
sys.exit()
arr[x][y] = snake_lon
for a, b in enumerate(arr, 1):
for c, d in enumerate(b, 1):
if (d > 0):
arr[a - 1][c - 1] = arr[a - 1][c - 1] - 1
pygame.draw.rect(screen, color_green, ((a - 1) * 10, (c - 1) * 10, 10, 10))
if (d < 0):
pygame.draw.rect(screen, color_red, ((a - 1) * 10, (c - 1) * 10, 10, 10))
if (x == foodx) and (y == foody):
snake_lon += 1
while (arr[foodx][foody] != 0):
foodx = random.randint(1, 60)
foody = random.randint(1, 40)
arr[foodx][foody] = -1
pygame.display.update()