大家好,今天我们要解答,python贪吃蛇代码和运行结果 python贪吃蛇完整代码不用库,现在让我们一起来看看吧!
今天我分享一个代码,贪吃蛇的代码,废话不多说,直接上原码
import pygame, sys
from pygame.locals import *
()
fpsClock = .Clock()
WINDOW = pygame.display.set_mode((400, 300))
pygame.display.set_caption('贪吃蛇')
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_position = [300, 150]
food_spawn = True
direction = 'RIGHT'
change_to = direction
def game_over():
()
()
while True:
for event in ():
if == QUIT:
game_over()
elif == KEYDOWN:
if == K_RIGHT or == ord('d'):
change_to = 'RIGHT'
if == K_LEFT or == ord('a'):
change_to = 'LEFT'
if == K_UP or == ord('w'):
change_to = 'UP'
if == K_DOWN or == ord('s'):
change_to = 'DOWN'
if == K_ESCAPE:
(pygame.event.Event(QUIT))
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_position[0] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_spawn = False
else:
()
if not food_spawn:
food_position = [pygame.randint(0, 39) * 10, pygame.randint(0, 29) * 10]
food_spawn = True
(BLACK)
for pos in snake_body:
(WINDOW, RED, (
pos[0], pos[1], 10, 10))
(WINDOW, WHITE, (
food_position[0], food_position[1], 10, 10))
if snake_position[0] >= 400 or snake_position[0] < 0:
game_over()
if snake_position[1] >= 300 or snake_position[1] < 0:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
pygame.display.update()
(12)
原文地址1:https://blog.youkuaiyun.com/2401_82970449/article/details/136121222
参考资料:python中用turtle画一个圆形 https://blog.youkuaiyun.com/SXIAOYAN_/article/details/140061099