高级玩家

- 贡献度
- 0
- 金元
- 3338
- 积分
- 334
- 精华
- 0
- 注册时间
- 2009-3-12
|
import pygame
import random
# 初始化 pygame
pygame.init()
# 定義常數
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
GRID_SIZE = 20
# 創建遊戲視窗
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('貪吃蛇')
# 創建顏色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 創建蛇類
class Snake:
def __init__(self):
self.body = [(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)]
self.direction = random.choice(['up', 'down', 'left', 'right'])
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= GRID_SIZE
elif self.direction == 'down':
y += GRID_SIZE
elif self.direction == 'left':
x -= GRID_SIZE
elif self.direction == 'right':
x += GRID_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, GREEN, (x, y, GRID_SIZE, GRID_SIZE))
# 創建食物類
class Food:
def __init__(self):
self.x = random.randint(0, WINDOW_WIDTH // GRID_SIZE - 1) * GRID_SIZE
self.y = random.randint(0, WINDOW_HEIGHT // GRID_SIZE - 1) * GRID_SIZE
def draw(self):
pygame.draw.rect(window, RED, (self.x, self.y, GRID_SIZE, GRID_SIZE))
# 創建主函數
def main():
snake = Snake()
food = Food()
clock = pygame.time.Clock()
score = 0
while True:
# 事件處理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction != 'down':
snake.direction = 'up'
elif event.key == pygame.K_DOWN and snake.direction != 'up':
snake.direction = 'down'
elif event.key == pygame.K_LEFT and snake.direction != 'right':
snake.direction = 'left'
elif event.key == pygame.K_RIGHT and snake.direction != 'left':
snake.direction = 'right'
# 遊戲邏輯
snake.move()
if snake.body[0][0] == food.x and snake.body[0][1] == food.y:
snake.body.append((food.x, food.y))
food = Food()
score += 10
if snake.body[0][0] < 0 or snake.body[0][0
|
|