用户:
ghhhhh查看:2 回复:1 评论:2 创建时间:2021-07-02T10:08:29
【作品展示】

【作品介绍】
这是我做的一个贪吃蛇游戏请大家帮我添加一段蛇碰到自己身体就结束游戏的代码
我是萌新,谢谢
【作品源代码】
import pygame
import sys
import random
from pygame.locals import*
red = pygame.Color(255, 0, 0)
white = pygame.Color(255, 255, 255)
black = pygame.Color(0, 0, 0)
def over():
pygame.quit()
sys.exit()
def main():
pygame.init()
size = 600, 600
fps = pygame.time.Clock()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("贪吃蛇")
snackposition = [100, 100]
snackbody = [[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:
changedirection = "right"
if event.key == K_LEFT:
changedirection = "left"
if event.key == K_UP:
changedirection = "up"
if event.key == K_DOWN:
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
if direction == "right":
snackposition[0] += 20
if direction == "left":
snackposition[0] -= 20
if direction == "up":
snackposition[1] -= 20
if direction == "down":
snackposition[1] += 20
snackbody.insert(0, list(snackposition))
if snackposition[0] == targetposition[0] and snackposition[1] == targetposition[1]:
targetflag = 0
else:
snackbody.pop()
if targetflag == 0:
x = random.randrange(1, 30)
y = random.randrange(1, 30)
targetposition = [int(x*20), int(y*20)]
targetflag = 1
screen.fill(black)
for position in snackbody:
pygame.draw.rect(screen, white, Rect(
position[0], position[1], 20, 20), 0)
pygame.draw.rect(screen, red, Rect(
targetposition[0], targetposition[1], 20, 20), 0)
pygame.display.flip()
if snackposition[0] > 600 or snackposition[0] < 0:
over()
if snackposition[1] > 580 or snackposition[1] < 0:
over()
fps.tick(8)
if __name__ == "__main__":
main()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn