[python]代码库
# -*- codeing = utf-8 -*-
# @Time:2020/10/21 20:16
# @File:贪吃蛇.py
# @Software:PyCharm
import pygame as p
import easygui
import random
import copy
def pause():
easygui.msgbox("点击按钮以开始游戏","贪吃蛇")
def MianLoop():
gameover = False
snake_list = [[10,10]]
food_point = [random.randint(10,490),random.randint(10,490)]
p.init()
icon = p.image.load("./images/icon.jpg")
screen = p.display.set_mode((500,500))
clock = p.time.Clock()
p.display.set_caption("贪吃蛇")
p.display.set_icon(icon)
move_up = False
move_down = False
move_left = False
move_right = False
pause()
score = 0
running = True
while running:
clock.tick(20)
screen.fill([50,50,50])
for e in p.event.get():
if e.type == p.QUIT:
import sys
sys.exit(0)
if e.type == p.KEYDOWN:
if move_down != True:
if e.key == p.K_w or e.key == p.K_UP:
move_up = True
move_down = False
move_left = False
move_right = False
if move_up != True:
if e.key == p.K_s or e.key == p.K_DOWN:
move_up = False
move_down = True
move_left = False
move_right = False
if move_right !=True:
if e.key == p.K_a or e.key == p.K_LEFT:
move_up = False
move_down = False
move_left = True
move_right = False
if move_left != True:
if e.key == p.K_d or e.key == p.K_RIGHT:
move_up = False
move_down = False
move_left = False
move_right = True
if e.key == p.K_SPACE:
pause()
pos = len(snake_list) - 1
while pos > 0:
snake_list[pos] = copy.deepcopy(snake_list[pos-1])
pos -= 1
if move_up:
snake_list[pos][1] -= 10
if snake_list[pos][1] < 0:
snake_list[pos][1] = 500
if move_down:
snake_list[pos][1] += 10
if snake_list[pos][1] > 500:
snake_list[pos][1] = 0
if move_left:
snake_list[pos][0] -= 10
if snake_list[pos][0] < 0:
snake_list[pos][0] = 500
if move_right:
snake_list[pos][0] += 10
if snake_list[pos][0] > 500:
snake_list[pos][0] = 0
food_reck = p.draw.circle(screen,[255,50,50],food_point,13,0)
for point in snake_list:
p.draw.circle(screen,[255,255,0],point,5,0)
snake_rect = []
for snake_pos in snake_list:
snake_rect.append(p.draw.circle(screen,[255,255,0],point,5,0))
if food_reck.collidepoint(snake_pos):
snake_list.append(food_point)
food_point = [random.randint(10,490),random.randint(10,490)]
score += 1
food_reck = p.draw.circle(screen,[255,50,50],food_point,13,0)
for snake in snake_list[1:]:
if snake[0] == snake_list[0][0] and snake[1] == snake_list[0][1]:
gameover = True
if gameover:
file = open("./data/data.data","r")
lszgfs = file.read()
file.close()
if len(snake_list) > int(lszgfs):
file = open("./data/data.data","w")
lszgfs = len(snake_list)
file.write(str(lszgfs))
file.close()
easygui.msgbox(f"游戏结束\n新纪录:{len(snake_list)}")
else:
easygui.msgbox(f"游戏结束\n分数:{len(snake_list)}\n历史最高分数:{lszgfs}")
file.close()
break
p.display.update()
if __name__ == "__main__":
while True:
MianLoop()
初级程序员
by: 54188 发表于:2021-07-24 11:00:08 顶(0) | 踩(0) 回复
麻烦把图片发一下
回复评论