使用IDLE软件python贪吃蛇代码
时间: 2024-05-16 20:14:58 浏览: 88
使用IDLE的Python shell窗口实例详解
下面是一个简单的贪吃蛇代码实现,你可以在IDLE软件中运行它:
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# 设置方格大小
BLOCK_SIZE = 10
class Snake:
def __init__(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x * BLOCK_SIZE)), (cur[1] + (y * BLOCK_SIZE)))
if new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
def handle_keys(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.turn(UP)
elif event.key == pygame.K_DOWN:
self.turn(DOWN)
elif event.key == pygame.K_LEFT:
self.turn(LEFT)
elif event.key == pygame.K_RIGHT:
self.turn(RIGHT)
class Food:
def __init__(self):
x = random.randrange(0, SCREEN_WIDTH, BLOCK_SIZE)
y = random.randrange(0, SCREEN_HEIGHT, BLOCK_SIZE)
self.position = (x, y)
self.color = RED
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
def draw_grid(surface):
for y in range(0, int(SCREEN_HEIGHT / BLOCK_SIZE)):
for x in range(0, int(SCREEN_WIDTH / BLOCK_SIZE)):
if (x + y) % 2 == 0:
r = pygame.Rect((x * BLOCK_SIZE, y * BLOCK_SIZE), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, WHITE, r)
else:
rr = pygame.Rect((x * BLOCK_SIZE, y * BLOCK_SIZE), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, BLACK, rr)
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def main():
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake")
snake = Snake()
food = Food()
running = True
while running:
clock.tick(10)
snake.handle_keys()
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
screen.fill(BLACK)
draw_grid(screen)
snake.draw(screen)
food.draw(screen)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
```
注意,需要在代码中安装 pygame 模块,命令为 `pip install pygame`。
阅读全文