用任意一种语言编写贪吃蛇代码
时间: 2023-03-10 16:53:08 浏览: 107
超简单贪吃蛇c语言代码编写.pdf
示例:我可以用Python来编写贪吃蛇代码。下面是一个简单的示例:import pygame
import random # Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0) # This class represents the snake
class Snake(object):
def __init__(self):
self.x_change = 0
self.y_change = 0
self.length = 1
self.positions = [(4, 0)] # Initialize pygame
pygame.init() # Set the width and height of the screen [width,height]
size = [800, 600]
screen = pygame.display.set_mode(size) # Set the title of the window
pygame.display.set_caption("贪吃蛇") # Create an object of the class snake
snake_obj = Snake() #Loop until the user clicks the close button.
done = False # Used to manage how fast the screen updates
clock = pygame.time.Clock() # -------- Main Program Loop -----------
while done == False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_obj.x_change = -10
snake_obj.y_change = 0
elif event.key == pygame.K_RIGHT:
snake_obj.x_change = 10
snake_obj.y_change = 0
elif event.key == pygame.K_UP:
snake_obj.x_change = 0
snake_obj.y_change = -10
elif event.key == pygame.K_DOWN:
snake_obj.x_change = 0
snake_obj.y_change = 10
# --- Game Logic
# Move the snake
snake_obj.positions[0] = (snake_obj.positions[0][0] + snake_obj.x_change, snake_obj.positions[0][1] + snake_obj.y_change)
# --- Drawing Code
# Set the screen background
screen.fill(BLACK)
# Draw the snake
for pos in snake_obj.positions:
pygame.draw.rect(screen, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
# Update the screen
pygame.display.flip()
# Limit to 20 frames per second
clock.tick(20) # Close the window and quit.
pygame.quit() 我可以用JavaScript来编写贪吃蛇代码。下面是一个简单的示例:// Initialize variables
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
let x = canvas.width/2;
let y = canvas.height-30;
let dx = 2;
let dy = -2;
let snakeSize = 10;
let length = 1;
let tail = []; // Draw snake
function drawSnake() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw tail
for (let i = 0; i < tail.length; i++) {
ctx.fillStyle = "green";
ctx.fillRect(tail[i].x, tail[i].y, snakeSize, snakeSize);
} // Draw head
ctx.fillStyle = "green";
ctx.fillRect(x, y, snakeSize, snakeSize);
} // Main game loop
function gameLoop() {
drawSnake();
x += dx;
y += dy;
requestAnimationFrame(gameLoop);
} gameLoop();
阅读全文