不多解释,好用才是王道,自己直接点链接观看,解释没意义。
http://aicnn.cn/loginPage?aff=UIYMg97xaZ
他的输出代码:
import pygame
import time
import random
pygame.init()
# 设置屏幕大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置标题
pygame.display.set_caption('贪吃虫游戏')
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 设置蛇的初始位置和大小
snake_block = 10
snake_speed = 15
# 设置食物的位置和大小
food_x = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
food_block = 10
# 设置蛇的初始长度
snake_list = []
length_of_snake = 1
# 设置方向
direction = "RIGHT"
change_to = direction
# 游戏主循环
game_over = False
while not game_over:
# 事件监听
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
elif event.key == pygame.K_ESCAPE:
game_over = True
# 改变方向
if change_to == "RIGHT" and not direction == "LEFT":
direction = "RIGHT"
if change_to == "LEFT" and not direction == "RIGHT":
direction = "LEFT"
if change_to == "UP" and not direction == "DOWN":
direction = "UP"
if change_to == "DOWN" and not direction == "UP":
direction = "DOWN"
# 移动蛇
if direction == "RIGHT":
snake_x += snake_block
if direction == "LEFT":
snake_x -= snake_block
if direction == "UP":
snake_y -= snake_block
if direction == "DOWN":
snake_y += snake_block
# 创建蛇的身体
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
# 检查是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
# 绘制蛇和食物
screen.fill(blue)
for segment in snake_list[:-1]:
pygame.draw.rect(screen, black, [segment[0], segment[1], snake_block, snake_block])
pygame.draw.rect(screen, green, [food_x, food_y, food_block, food_block])
# 绘制蛇头
pygame.draw.rect(screen, red, [snake_x, snake_y, snake_block, snake_block])
# 更新屏幕
pygame.display.update()
# 设置游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 检查游戏是否结束
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over = True
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
pygame.quit()
quit()