1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| import pygame import random
pygame.init()
window_width = 800 window_height = 600 window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Python 贪食蛇')
white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0)
snake_block_size = 10 snake_speed = 15 snake_list = [] snake_length = 1 snake_x = window_width / 2 snake_y = window_height / 2 snake_x_change = 0 snake_y_change = 0
food_block_size = 10 food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
font_style = pygame.font.SysFont(None, 30)
def score(score): value = font_style.render('Score: ' + str(score), True, black) window.blit(value, [0, 0])
def draw_snake(snake_block_size, snake_list): for x in snake_list: pygame.draw.rect(window, green, [x[0], x[1], snake_block_size, snake_block_size])
def message(msg, color): mesg = font_style.render(msg, True, color) window.blit(mesg, [window_width / 6, window_height / 3])
game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True
if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake_x_change = -snake_block_size snake_y_change = 0 elif event.key == pygame.K_RIGHT: snake_x_change = snake_block_size snake_y_change = 0 elif event.key == pygame.K_UP: snake_y_change = -snake_block_size snake_x_change = 0 elif event.key == pygame.K_DOWN: snake_y_change = snake_block_size snake_x_change = 0 if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0: game_over = True
snake_x += snake_x_change snake_y += snake_y_change
window.fill(white)
pygame.draw.rect(window, red, [food_x, food_y, food_block_size, food_block_size])
snake_head = [] snake_head.append(snake_x) snake_head.append(snake_y) snake_list.append(snake_head) if len(snake_list) > snake_length: del snake_list[0]
for x in snake_list[:-1]: if x == snake_head: game_over = True
draw_snake(snake_block_size, snake_list) score(snake_length - 1)
pygame.display.update()
if snake_x == food_x and snake_y == food_y: food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0 food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0 snake_length += 1
pygame.display.update()
clock = pygame.time.Clock() clock.tick(snake_speed)
pygame.quit()
quit()
|