Python3 39行 贪吃蛇

import pygame,sys,random
from pygame.locals import *
if __name__ == "__main__":
    pygame.init()  # 初始化
    GameWindow = pygame.display.set_mode((640, 480))  # Initialize a window or screen for display
    snakeHeader = [100, 100]
    snakeBody = [[100, 100], [80, 100], [60, 100]]
    Food = [300, 300]
    direction = K_RIGHT  # 默认向右

    while 1:
        pygame.time.Clock().tick(2)  # By calling Clock.tick(40) , the program will never run at more than 40 frames per second.
        for event in pygame.event.get():  # 检测按键事件
            if event.type == KEYDOWN:
                direction = event.key  # 判断键盘事件
            if event.type == QUIT:
                sys.exit()

        if direction == K_RIGHT:  # 根据方向移动蛇头的坐标
            snakeHeader[0] += 20
        elif direction == K_LEFT:
            snakeHeader[0] -= 20
        elif direction == K_UP:
            snakeHeader[1] -= 20
        elif direction == K_DOWN:
            snakeHeader[1] += 20

        snakeBody.insert(0, list(snakeHeader))  # 增加蛇的长度
        if snakeHeader[0] == Food[0] and snakeHeader[1] == Food[1]:  # 判断是否吃掉了食物,这里未进行碰撞检测
            x = random.randrange(1, 32)
            y = random.randrange(1, 24)
            Food = [int(x * 20), int(y * 20)]
        else:
            snakeBody.pop()

        GameWindow.fill(pygame.Color(0, 0, 0))  # 绘制背景
        for position in snakeBody:
            whiteColour = pygame.Color(255, 255, 255)
            pygame.draw.rect(GameWindow, whiteColour, Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(GameWindow, whiteColour, Rect(Food[0], Food[1], 20, 20))

        pygame.display.flip()  # Update the full display Surface to the screen
        if snakeHeader[0] > 620 or snakeHeader[0] < 0 or snakeHeader[1] > 460 or snakeHeader[1] < 0:  # 判断是否撞到边界
            sys.exit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值