python低配贪食蛇

那是一个无聊的下午,无聊的我看着无聊的py教程,了解到pygame这个奇妙的库后,我忽然想做一个无聊的贪食蛇玩玩。。于是

#v0.1 ByDOGGOD_Q
import pygame
from random import randint
import time


def main():
    pygame.init()
    screen = pygame.display.set_mode((400, 400))
    pygame.display.set_caption('EATSNAKE')
    screen.fill((255, 255, 255))
    running = True
    snake = [(0, 0)] #蛇身,利用队列,数越大越靠前
    #bo = [[0] * 41 for i in range(41)]
    st = pygame.image.load('START.jpg') #导入开始按钮
    screen.blit(st, (100, 100))
    pygame.display.flip()
    start = 0 #是否开始
    while start == 0:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = event.pos
                if x >= 100 and x <= 300 and y >= 100 and y <= 200:
                    start = 1
    screen.fill((255, 255, 255))
    bo = [[0 for i in range(1, 41)] for j in range(1, 41)]
    bo[1][1] = 1
    pygame.draw.rect(screen, (0, 0, 0),(0, 0, 10, 10), 0)
    way = 100 #前进方向
    x, y = randint(1, 39), randint(1, 39)
    while bo[x][y] == 1:
        x, y = randint(1, 40), randint(1, 40)
    pygame.draw.rect(screen, (255, 0, 0), (x * 10, y * 10, 10, 10), 0)
    pygame.display.flip()
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN and (event.key == 119 or event.key == 97 or event.key == 115 or event.key ==100):
                way = event.key
        l = len(snake)
        if way == 119:
            snake.append((snake[l-1][0] % 40, (snake[l-1][1]-1) % 40))
        if way == 97:
            snake.append(((snake[l-1][0]-1) % 40, snake[l-1][1] % 40))
        if way == 115:
            snake.append((snake[l-1][0] % 40, (snake[l-1][1]+1) % 40))
        if way == 100:
            snake.append(((snake[l-1][0]+1) % 40, snake[l-1][1] % 40))
        pygame.draw.rect(screen, (0, 0, 0), (snake[l][0]*10, snake[l][1]*10, 10, 10), 0)
        if bo[snake[l][0]][snake[l][1]] == 1:
            time.sleep(3)
            running = False
            break

        bo[snake[l][0]][snake[l][1]] = 1
        if snake[l] == (x, y):
            x, y = randint(0, 39), randint(0, 39)
            while bo[x][y] == 1:
                x, y = randint(0, 39), randint(0, 39)
            pygame.draw.rect(screen, (255, 0, 0), (x * 10, y * 10, 10, 10), 0)
        else:
            pygame.draw.rect(screen, (255, 255, 255), (snake[0][0]*10, snake[0][1]*10, 10, 10), 0)
            bo[snake[0][0]][snake[0][1]] = 0
            del snake[0]
        pygame.display.flip()
        time.sleep(0.1)

        


if __name__ == '__main__':
    main()

        
        
        
START.jpg START.jpg

 

这个只是一个小尝试,把它发在博客上很大程度是由于自己的虚荣心。这是我做的第一个像样的游戏,小蛇第一次动起来的样子我可能一辈子都不会忘。希望这是一个开始。如果有时间的话代码会继续优化,因为有好多想法还没有实现。

你可能感兴趣的:(水,Py小游戏)