Commit dcfcd195 by BellCodeEditor

auto save

parent 20a2c085
Showing with 85 additions and 21 deletions
import pygame import pygame
from pygame import locals import random
# 初始化pygame,为使用pygame做准备 caption_width = 500 #画布宽度
pygame.init() caption_height = 500 #画布高度
FPSCLOCK = pygame.time.Clock() white_color = (255, 255, 255) # 白色rgb
# 创建一个窗口 black_color = (0, 0, 0)
screen = pygame.display.set_mode((660,480),0,32) game_title = '蛇蛇兄弟'
background = pygame.image.load("bg.png") cell = 10 # 格子
apple = pygame.image.load("apple.png") snake_init_pos = [[250,250], [240,250], [230,250], [220,250]] # 蛇的初始位置
body = pygame.image.load("body.png") food_pos = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10] # 食物初始随机位置
down = pygame.image.load("down.png") head_pos = [250, 250]
left = pygame.image.load("left.png")
right = pygame.image.load("right.png") pygame.init() # 初始化 pygame
clock = pygame.time.Clock()
x, y = 240,120
caption = pygame.display.set_mode((caption_width, caption_height))
while True: pygame.display.set_caption(game_title)
for event in pygame.event.get():
print(event) def draw_rect(color, position):
if event.type == locals.QUIT: pygame.draw.rect(caption, color, pygame.Rect(position[0], position[1], cell, cell))
exit()
def hit_the_self():
if snake_init_pos[0] in snake_init_pos[1:]:
return True
else:
return False
def hit_the_wall(head_pos):
if head_pos[0] >= caption_width or head_pos[0]<0 or head_pos[1] >= caption_height or head_pos[1] < 0:
return True
else:
return False
def change_direction(head_pos):
global food_pos
snake_init_pos.insert(0, list(head_pos))
if head_pos != food_pos:
snake_init_pos.pop()
else:
food_pos = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
if hit_the_self() or hit_the_wall(head_pos):
# 给我死
pygame.quit()
def main():
for pos in snake_init_pos:
draw_rect(white_color, pos)
draw_rect(white_color, food_pos)
pygame.display.update() pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
head_pos[0] -= cell
change_direction(head_pos)
elif event.key == pygame.K_RIGHT:
head_pos[0] += cell
change_direction(head_pos)
elif event.key == pygame.K_UP:
head_pos[1] -= cell
change_direction(head_pos)
elif event.key == pygame.K_DOWN:
head_pos[1] += cell
change_direction(head_pos)
caption.fill(black_color)
draw_rect(white_color, food_pos)
for pos in snake_init_pos:
draw_rect(white_color, pos)
pygame.display.update()
clock.tick(300)
if __name__ == '__main__':
main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment