python最简单的贪吃蛇游戏

import pygame, sys, random, time
from pygame.locals import *                    
pygame.init()                                  
Clock = pygame.time.Clock()
screen = pygame.display.set_mode((1200, 900))
pygame.display.set_caption('贪吃蛇游戏')
direct = 'right' ; GameOver = False                          
food = [10, 4] ; head = [4, 4] ; snake= [ [4, 4], [3, 4], [2, 4]]                         
font = pygame.font.SysFont("MicrosoftYaHei", 200).render('游戏结束', True, (10, 255, 10))
while True:
    Clock.tick(10)                            
    screen.fill((28, 56, 20))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_UP or event.key == K_w:
                if direct != 'bottom':  direct = 'top'
            if event.key == K_DOWN or event.key == K_s:
                if direct != 'top' :    direct = 'bottom'
            if event.key == K_LEFT or event.key == K_a:
                if direct != 'right' :  direct = 'left'
            if event.key == K_RIGHT or event.key == K_d:
                if direct != 'left':    direct = 'right'
    if direct == 'left':   head[0] -= 1
    if direct == 'right':  head[0] += 1
    if direct == 'top':    head[1] -= 1
    if direct == 'bottom': head[1] += 1
    if head[0] < 0 or head[0] > 40 or head[1] < 0 or head[1] > 30:
        GameOver = True     
    if head in snake[1:]:        GameOver = True
    if GameOver:
        screen.blit(font, (200,300))
        pygame.display.flip()
        time.sleep(2)
        pygame.quit()
        sys.exit()         
    snake.insert(0, list(head))
    if head == food:
        while True:
            food = [int(random.randrange(1,39)), int(random.randrange(1,29))]
            if food not in snake:
                break
    else:
        snake.pop()
    pygame.draw.rect(screen, (255,34 , 20), Rect(food[0]*30, food[1]*30, 30, 30))
    for body in snake:
        pygame.draw.rect(screen, (255, 144, 20), Rect(body[0]*30, body[1]*30, 29, 29))
    pygame.display.flip()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值