当前位置:   article > 正文

代码小游戏

代码小游戏

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()
}
  • 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
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160

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 的绘图函数来绘制游戏界面,并使用字体来显示得分。
希望这可以帮助您开始编写您自己的贪吃蛇游戏!
'''
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/769115
推荐阅读
相关标签
  

闽ICP备14008679号