代码小游戏

Go

  • 贪吃蛇
package main

import (
	"math/rand"
	"time"

	"github.com/nsf/termbox-go"
)

const (
	width  = 40
	height = 20
)

type point struct {
	x, y int
}

type snake struct {
	body []point
	dir  point
}

var (
	snakeObj snake
	food     point
	score    int
	gameOver bool
)

func main() {
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	rand.Seed(time.Now().UnixNano())

	snakeObj = snake{
		body: []point{{20, 10}, {19, 10}, {18, 10}},
		dir:  point{1, 0},
	}

	placeFood()

	draw()

	eventQueue := make(chan termbox.Event)
	go func() {
		for {
			eventQueue <- termbox.PollEvent()
		}
	}()

gameLoop:
	for {
		select {
		case ev := <-eventQueue:
			if ev.Type == termbox.EventKey {
				switch ev.Key {
				case termbox.KeyArrowUp:
					if snakeObj.dir.y != 1 {
						snakeObj.dir = point{0, -1}
					}
				case termbox.KeyArrowDown:
					if snakeObj.dir.y != -1 {
						snakeObj.dir = point{0, 1}
					}
				case termbox.KeyArrowLeft:
					if snakeObj.dir.x != 1 {
						snakeObj.dir = point{-1, 0}
					}
				case termbox.KeyArrowRight:
					if snakeObj.dir.x != -1 {
						snakeObj.dir = point{1, 0}
					}
				case termbox.KeyEsc:
					break gameLoop
				}
			}
		default:
			if gameOver {
				continue
			}

			next := snakeObj.body[0]
			next.x += snakeObj.dir.x
			next.y += snakeObj.dir.y

			if next.x < 0 || next.x >= width || next.y < 0 || next.y >= height {
				gameOver = true
				continue
			}

			for _, p := range snakeObj.body {
				if p == next {
					gameOver = true
					break
				}
			}

			if next == food {
				score++
				snakeObj.body = append([]point{next}, snakeObj.body...)
				placeFood()
			} else {
				snakeObj.body = append([]point{next}, snakeObj.body[:len(snakeObj.body)-1]...)
			}

			draw()

			time.Sleep(time.Second / 10)
		}
	}
}

func placeFood() {
	for {
		food = point{rand.Intn(width), rand.Intn(height)}
		for _, p := range snakeObj.body {
			if p == food {
				continue
			}
		}
		break
	}
}

func draw() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	for _, p := range snakeObj.body {
		termbox.SetCell(p.x, p.y, '█', termbox.ColorGreen, termbox.ColorDefault)
	}

	termbox.SetCell(food.x, food.y, '●', termbox.ColorRed, termbox.ColorDefault)

	if gameOver {
		termbox.SetCell(width/2-4, height/2, 'G', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2-3, height/2, 'A', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2-2, height/2, 'M', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2-1, height/2, 'E', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2, height/2, ' ', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2+1, height/2, 'O', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2+2, height/2, 'V', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2+3, height/2, 'E', termbox.ColorDefault, termbox.ColorDefault)
		termbox.SetCell(width/2+4, height/2, 'R', termbox.ColorDefault, termbox.ColorDefault)
	}

	termbox.SetCell(0, height, 'S', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(1, height, 'C', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(2, height, 'O', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(3, height, 'R', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(4, height, 'E', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(6, height, rune(score/10)+'0', termbox.ColorDefault, termbox.ColorDefault)
	termbox.SetCell(7, height, rune(score%10)+'0', termbox.ColorDefault, termbox.ColorDefault)

	termbox.Flush()
}

Python

  • 贪吃蛇
#!/usr/bin/env python3

import pygame # pip3 install pygame
import random

# 初始化 Pygame
pygame.init()

# 设置游戏窗口的大小
WINDOW_WIDTH = 2300
WINDOW_HEIGHT = 1700
WINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)

# 设置游戏窗口的标题
pygame.display.set_caption("贪吃蛇游戏")

# 创建游戏窗口
screen = pygame.display.set_mode(WINDOW_SIZE)

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 192, 203)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 定义蛇的初始位置和大小
SNAKE_SIZE = 20
SNAKE_X = WINDOW_WIDTH / 2
SNAKE_Y = WINDOW_HEIGHT / 2
SNAKE_SPEED = 20

# 定义食物的初始位置和大小
FOOD_SIZE = 20
FOOD_X = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
FOOD_Y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)

# 定义蛇的初始长度和方向
snake_length = 10
snake_direction = "right"
snake_body = []

# 定义游戏循环标志
game_over = False

# 定义游戏时钟
clock = pygame.time.Clock()

# 定义字体
font = pygame.font.SysFont(None, 48)

# 定义得分
score = 0

# 游戏循环
while not game_over:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        elif event.type == pygame.KEYDOWN:
            if 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"
            elif 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"

    # 移动蛇的身体
    if snake_direction == "right":
        SNAKE_X += SNAKE_SPEED
    elif snake_direction == "left":
        SNAKE_X -= SNAKE_SPEED
    elif snake_direction == "up":
        SNAKE_Y -= SNAKE_SPEED
    elif snake_direction == "down":
        SNAKE_Y += SNAKE_SPEED

    # 检查蛇是否撞到了墙壁
    if SNAKE_X < 0 or SNAKE_X > WINDOW_WIDTH - SNAKE_SIZE or SNAKE_Y < 0 or SNAKE_Y > WINDOW_HEIGHT - SNAKE_SIZE:
        game_over = True

    # 检查蛇是否吃到了食物
    if SNAKE_X < FOOD_X + FOOD_SIZE and SNAKE_X + SNAKE_SIZE > FOOD_X and SNAKE_Y < FOOD_Y + FOOD_SIZE and SNAKE_Y + SNAKE_SIZE > FOOD_Y:
        FOOD_X = random.randint(0, WINDOW_WIDTH - FOOD_SIZE)
        FOOD_Y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE)
        snake_length += 1
        score += 10

    # 更新蛇的身体
    snake_head = [SNAKE_X, SNAKE_Y]
    snake_body.append(snake_head)
    if len(snake_body) > snake_length:
        del snake_body[0]

    # # 检查蛇是否撞到了自己的身体
    # for body_part in snake_body[:-1]:
    #     if body_part == snake_head:
    #         game_over = True

    # 绘制游戏界面
    screen.fill(BLACK)
    pygame.draw.rect(screen, GREEN, [FOOD_X, FOOD_Y, FOOD_SIZE, FOOD_SIZE])
    for body_part in snake_body:
        pygame.draw.rect(screen, WHITE, [body_part[0], body_part[1], SNAKE_SIZE, SNAKE_SIZE])
    score_text = font.render("得分:" + str(score), True, RED)
    screen.blit(score_text, [10, 10])
    pygame.display.update()

    # 控制游戏帧率, 随着 积分的增加, 游动的速度越快
    # clock.tick(10)
    speed = 10 if score == 0 else score
    clock.tick(speed)

# 退出 Pygame
pygame.quit()

'''
在这个示例代码中,我们使用 Pygame 库来创建游戏窗口,并处理游戏事件。
我们定义了蛇和食物的初始位置和大小,并使用循环来移动蛇和检查游戏结束的条件。
我们还使用 Pygame 的绘图函数来绘制游戏界面,并使用字体来显示得分。
希望这可以帮助您开始编写您自己的贪吃蛇游戏!
'''

你可能感兴趣的:(python,go,游戏)