用户:
蓝雀Anywhere查看:0 回复:1 评论:0 创建时间:2022-01-25T20:45:46
【作品展示】

【作品介绍】
大家好,我是Python学员,今天用Pygame打造了一个贪吃蛇,玩不需要依赖图片,用代码直接玩,我是DoDo,谢谢大家支持,路过的大哥哥大姐姐们给个三连呗!
【作品源代码】
import easygui
import pygame
import sys
import random
from pygame.locals import *
pinkColor = pygame.Color(255, 182, 193)
blackColor = pygame.Color(0, 0, 0)
whiteColor = pygame.Color(255, 255, 255)
def ynbox():
if easygui.ynbox('你失败了,是否重启', 'Pygame Window', ('重启', '退出')):
main()
else:
gameover()
def gameover():
pygame.quit()
sys.exit()
def main():
pygame.init()
time_clock = pygame.time.Clock()
screen = pygame.display.set_mode((喵0, 480))
pygame.display.set_caption("贪吃蛇")
snakePosition = [100, 100]
snakeSegments = [[100, 100], [80, 100], [60, 100], [40, 100], [20, 100]]
foodPostion = [300, 300]
foodTotal = 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 == K_d:
changeDirection = 'right'
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0, list(snakePosition))
if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]:
foodTotal = 0
else:
snakeSegments.pop()
if foodTotal == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
foodPostion = [int(x * 20), int(y * 20)]
foodTotal = 1
screen.fill(blackColor)
for position in snakeSegments:
pygame.draw.rect(screen, pinkColor, Rect(
position[0], position[1], 20, 20))
pygame.draw.rect(screen, whiteColor, Rect(
foodPostion[0], foodPostion[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
ynbox()
elif snakePosition[1] > 460 or snakePosition[1] < 0:
ynbox()
for body in snakeSegments[1:]:
if snakePosition[0] == body[0] and snakePosition[1] == body[1]:
ynbox()
time_clock.tick(5)
if __name__ == '__main__':
main()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn