Commit 00c2fb6b by BellCodeEditor

auto save

parent dcfcd195
Showing with 30 additions and 85 deletions
import pygame import pygame
import random from pygame import locals
caption_width = 500 #画布宽度 # 初始化pygame,为使用pygame做准备
caption_height = 500 #画布高度 pygame.init()
white_color = (255, 255, 255) # 白色rgb FPSCLOCK = pygame.time.Clock()
black_color = (0, 0, 0) # 创建一个窗口
game_title = '蛇蛇兄弟' screen = pygame.display.set_mode((660,480),0,32)
cell = 10 # 格子 background = pygame.image.load("bg.png")
snake_init_pos = [[250,250], [240,250], [230,250], [220,250]] # 蛇的初始位置 apple = pygame.image.load("apple.png")
food_pos = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10] # 食物初始随机位置 body = pygame.image.load("body.png")
head_pos = [250, 250] down = pygame.image.load("down.png")
left = pygame.image.load("left.png")
pygame.init() # 初始化 pygame right = pygame.image.load("right.png")
clock = pygame.time.Clock()
x, y = 240,120
caption = pygame.display.set_mode((caption_width, caption_height))
pygame.display.set_caption(game_title) while True:
for event in pygame.event.get():
def draw_rect(color, position): if event.type == locals.QUIT:
pygame.draw.rect(caption, color, pygame.Rect(position[0], position[1], cell, cell)) exit()
#if event.type == locals.KEYDOWN:
def hit_the_self(): y += 30
if snake_init_pos[0] in snake_init_pos[1:]: screen.blit(background,(0,0))
return True screen.blit(right,(x,y))
else: screen.blit(body,(x-30,y))
return False screen.blit(body,(x-60,y))
screen.blit(body,(x-90,y))
def hit_the_wall(head_pos): screen.blit(apple,(200,120))
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()
FPSCLOCK.tick(3)
while 1: \ No newline at end of file
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