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()
Python3 39行 贪吃蛇
最新推荐文章于 2024-05-25 12:36:34 发布