import pygame, sys, random
from pygame.locals import *
redColour = pygame.Color(255, 0, 0) # 红色颜色对象
blackColour = pygame.Color(0, 0, 0) # 黑色颜色对象
whiteColour = pygame.Color(255, 255, 255) # 白色颜色对象
def gameOver(): # 游戏结束函数,退出程序
pygame.quit()
sys.exit()
def main(): # 主函数
pygame.init() # 初始化pygame
fpsClock = pygame.time.Clock() # 创建游戏帧数定时器
playSurface = pygame.display.set_mode((640, 480)) # 创建游戏界面的大小
pygame.display.set_caption('贪吃蛇') # 创建游戏标题
snakePosition = [100, 100] # 蛇头的坐标
snakeBody = [[100, 100], [80, 100], [60, 100]] # 蛇体的坐标
targetPosition = [300, 300] # 目标方块的坐标
targetflag = 1 # 目标方块的标记
direction = 'right' # 蛇头的方向
changeDirection = direction # 变化后的方向
while True: # 游戏循环
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
# 3.7 根据方向移动蛇头的坐标
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeBody.insert(0, list(snakePosition))
if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]:
targetflag = 0
else:
snakeBody.pop()
if targetflag == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
targetPosition = [int(x * 20), int(y * 20)]
targetflag = 1
playSurface.fill(blackColour)
for position in snakeBody: # rect(Surface, color, Rect, width=0)
pygame.draw.rect(playSurface, whiteColour, Rect(position[0], position[1], 20, 20)) # 画蛇
pygame.draw.rect(playSurface, redColour, Rect(targetPosition[0], targetPosition[1], 20, 20)) # 画目标方块
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
elif snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
fpsClock.tick(5)
if __name__ == "__main__":
main()
python--贪吃蛇小游戏
于 2023-12-25 21:13:52 首次发布
本文详细介绍了如何使用Python的pygame库开发一个基本的贪吃蛇游戏,包括游戏初始化、事件处理、蛇的移动和碰撞检测等关键部分。
摘要由CSDN通过智能技术生成