欢迎光临散文网 会员登陆 & 注册

python

2023-05-19 16:43 作者:Allstarboy  | 我要投稿

import pygame

import random


# 初始化pygame

pygame.init()


# 设置游戏窗口大小

screen_width = 600

screen_height = 400

screen = pygame.display.set_mode((screen_width, screen_height))


# 设置游戏标题

pygame.display.set_caption("My Game")


# 定义颜色

white = (255, 255, 255)

black = (0, 0, 0)

red = (255, 0, 0)


# 定义游戏角色

player = pygame.Rect(300, 350, 50, 50)

enemy = pygame.Rect(random.randint(0, screen_width-50), 0, 50, 50)


# 设置游戏时钟

clock = pygame.time.Clock()


# 游戏循环

while True:

    # 处理游戏事件

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            pygame.quit()

            quit()


    # 移动角色

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and player.x > 0:

        player.x -= 5

    if keys[pygame.K_RIGHT] and player.x < screen_width-50:

        player.x += 5


    # 移动敌人

    enemy.y += 5

    if enemy.y > screen_height:

        enemy.x = random.randint(0, screen_width-50)

        enemy.y = 0


    # 检测碰撞

    if player.colliderect(enemy):

        pygame.quit()

        quit()


    # 绘制游戏界面

    screen.fill(white)

    pygame.draw.rect(screen, black, player)

    pygame.draw.rect(screen, red, enemy)

    pygame.display.update()


    # 控制游戏帧率

    clock.tick(60)



python的评论 (共 条)

分享到微博请遵守国家法律