我在论坛看到有人让AI写剪刀石头布的小游戏。
我就试了下让他跑个贪吃蛇的小游戏,刚开始总是有些数组越界的小问题。
多试了几次后,就出来一个直接能运行起来玩的python代码了。
有点惊讶的是,AI给的代码很整洁,注释也清楚,我从没写过游戏的人 ,居然能看懂 有点震撼。
我只说了一句话: “用python实现一个贪吃蛇小游戏” 这就有点屌了。
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏界面大小、背景图片及标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('贪吃蛇')
# 定义颜色变量
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
# 定义游戏结束函数
def game_over():
pygame.quit()
exit()
# 定义主函数
def main():
# 初始化变量
snake_position = [100, 100]
snake_body = [[100, 100], [80, 100], [60, 100]]
target_position = [300, 300]
target_flag = 1
direction = 'RIGHT'
change_direction = direction
# 定义计时器
clock = pygame.time.Clock()
# 游戏主循环
while True:
# 处理游戏退出
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
game_over()
elif event.key == pygame.K_LEFT:
change_direction = 'LEFT'
elif event.key == pygame.K_RIGHT:
change_direction = 'RIGHT'
elif event.key == pygame.K_UP:
change_direction = 'UP'
elif event.key == pygame.K_DOWN:
change_direction = 'DOWN'
# 判断移动方向是否相反
if change_direction == 'LEFT' and not direction == 'RIGHT':
direction = change_direction
elif change_direction == 'RIGHT' and not direction == 'LEFT':
direction = change_direction
elif change_direction == 'UP' and not direction == 'DOWN':
direction = change_direction
elif change_direction == 'DOWN' and not direction == 'UP':
direction = change_direction
# 根据移动方向修改蛇头坐标
if direction == 'LEFT':
snake_position[0] -= 20
elif direction == 'RIGHT':
snake_position[0] += 20
elif direction == 'UP':
snake_position[1] -= 20
elif direction == 'DOWN':
snake_position[1] += 20
# 增加蛇的长度
snake_body.insert(0, list(snake_position))
if snake_position[0] == target_position[0] and snake_position[1] == target_position[1]:
target_flag = 0
else:
snake_body.pop()
# 重新生成目标方块
if not target_flag:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
target_position = [int(x * 20), int(y * 20)]
target_flag = 1
# 绘制pygame显示层
screen.fill(black)
for position in snake_body:
pygame.draw.rect(screen, green, pygame.Rect(
position[0], position[1], 20, 20))
pygame.draw.rect(screen, white, pygame.Rect(
target_position[0], target_position[1], 20, 20))
# 刷新pygame显示层
pygame.display.update()
# 判断是否死亡
if snake_position[0] < 0 or snake_position[0] > 780:
game_over()
elif snake_position[1] < 0 or snake_position[1] > 580:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
# 控制游戏速度
clock.tick(5)
# 运行主函数
main()
上一篇:
这是屎吗?我是吃还是不吃?下一篇:
下班路上玩玩机