Python教程

python pygame 贪吃蛇

本文主要是介绍python pygame 贪吃蛇,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import pygame
import sys
import random

pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption('snake')
direct = [0, 1]
body = []

for i in range(3, 8):
    body.append([4, i])

head = [4, 7]

clock = 0

blank = []
for i in range(20):
    for j in range(20):
        if not [i, j] in body:
            blank.append([i, j])

food = random.choice(blank)

while True:
    pygame.time.delay(20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == ord('a'):
                new = [0, -1]
            elif event.key == ord('d'):
                new = [0, 1]
            elif event.key == ord('w'):
                new = [-1, 0]
            elif event.key == ord('s'):
                new = [1, 0]
            else:
                continue
            if direct[0] == new[0] or direct[1] == new[1]:
                continue
            direct = new[:]
    clock += 1
    if clock >= 15:
        clock = 0
        old = [body[len(body)-1][0], body[len(body)-1][1]]
        head = [old[0] + direct[0], old[1] + direct[1]]
        if food == head:
            blank = []
            for i in range(20):
                for j in range(20):
                    if not [i, j] in body:
                        blank.append([i, j])

            food = random.choice(blank)
        else:
            del body[0]
        if head in body:
            pygame.quit()
            sys.exit()
        if not (0 <= head[0] < 20) or not (0 <= head[1] < 20):
            pygame.quit()
            sys.exit()
        body.append(head)
    screen.fill((0, 0, 0))
    for i in body:
        pygame.draw.rect(screen, (200, 200, 200), (20*i[1], 20*i[0], 20, 20))
    pygame.draw.rect(screen, (100, 170, 255), (20*food[1], 20*food[0], 20, 20))
    pygame.draw.rect(screen, (255, 255, 255), (20 * head[1], 20 * head[0], 20, 20))
    pygame.display.update()

 

这篇关于python pygame 贪吃蛇的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!