以下是一个类似跳一跳小游戏的简单代码示例:

import pygame
import random

# 游戏窗口大小
WIDTH = 800
HEIGHT = 600

# 方块大小
BLOCK_SIZE = 50

# 方块起始位置
BLOCK_START_X = WIDTH // 2 - BLOCK_SIZE // 2
BLOCK_START_Y = HEIGHT - BLOCK_SIZE

# 跳跃力度
JUMP_POWER = 10

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 36)

        self.block_x = BLOCK_START_X
        self.block_y = BLOCK_START_Y
        self.jump_power = JUMP_POWER
        self.score = 0

    def run(self):
        running = True

        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.jump()

            self.update()
            self.draw()
            pygame.display.flip()
            self.clock.tick(30)

        pygame.quit()

    def jump(self):
        self.block_y -= self.jump_power

    def update(self):
        self.jump_power -= 1  # 模拟重力
        self.block_y += self.jump_power  # 更新方块位置

        if self.block_y >= BLOCK_START_Y:  # 方块落地
            self.block_y = BLOCK_START_Y
            self.jump_power = JUMP_POWER

        if self.block_x >= WIDTH:  # 方块到达右边界
            self.block_x = 0
            self.score += 1

    def draw(self):
        self.screen.fill((255, 255, 255))  # 清空屏幕

        pygame.draw.rect(self.screen, (0, 0, 0), (self.block_x, self.block_y, BLOCK_SIZE, BLOCK_SIZE))  # 绘制方块

        score_text = self.font.render("Score: {}".format(self.score), True, (0, 0, 0))  # 绘制得分文本
        self.screen.blit(score_text, (10, 10))

if __name__ == "__main__":
    game = Game()
    game.run()

这个代码使用Pygame库来创建游戏窗口,并实现方块的跳跃和得分计算功能。玩家通过按下空格键来控制方块跳跃,跳跃时会受到重力的影响。方块每次跳跃到达窗口右边界时,得分增加1,并且方块会从窗口左边界重新开始跳跃。游戏界面显示当前得分

写一个类似跳一跳小游戏的代码

原文地址: https://www.cveoy.top/t/topic/iVMK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录