1 Star 1 Fork 0

kamiba/python_big_game

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main01.py 2.26 KB
一键复制 编辑 原始数据 按行查看 历史
songbo 提交于 2022-08-29 10:56 . Refactor Code
import pygame
import time
import sys
from enum import Enum
BG_COLOR = (200,200,200)
PLAYER_COLOR = (200,100,100)
SCREEN_SIZE = (500,500)
PLAYER_SPEED = 9
PLAYER_SIZE = (50, 50)
PLAYER_START_POS = (100, 400)
class Box:
def __init__(self, start_pos, size):
self.x = start_pos[0]
self.y = start_pos[1]
self.w = size[0]
self.h = size[1]
def rect(self):
return (self.x,self.y,self.w,self.h)
class PlayerBox:
def __init__(self, box, direction, speed, max_speed):
self.box = box
self.direction = direction
self.speed = speed
self.max_speed = max_speed
def set_moving_in_dir(self, direction):
self.direction = direction
self.speed = self.max_speed
def set_not_moving(self):
self.speed = 0
class Direction(Enum):
LEFT = 1
RIGHT = 2
UP = 3
DOWN = 4
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
player = PlayerBox(Box(PLAYER_START_POS,PLAYER_SIZE), Direction.RIGHT, 0, PLAYER_SPEED)
clock = pygame.time.Clock()
FPS=30
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.set_moving_in_dir(Direction.LEFT)
elif event.key == pygame.K_RIGHT:
player.set_moving_in_dir(Direction.RIGHT)
elif event.key == pygame.K_UP:
player.set_moving_in_dir(Direction.UP)
elif event.key == pygame.K_DOWN:
player.set_moving_in_dir(Direction.DOWN)
speed = PLAYER_SPEED
if event.type == pygame.KEYUP:
player.set_not_moving()
if player.direction == Direction.LEFT:
player.box.x = max(player.box.x - player.speed, 0)
elif player.direction == Direction.RIGHT:
player.box.x = min(player.box.x + player.speed, SCREEN_SIZE[0] - player.box.w)
elif player.direction == Direction.UP:
player.box.y = max(player.box.y - player.speed, 0)
elif player.direction == Direction.DOWN:
player.box.y = min(player.box.y + player.speed, SCREEN_SIZE[1] - player.box.h)
screen.fill(BG_COLOR)
pygame.draw.rect(screen,PLAYER_COLOR,player.box.rect())
pygame.display.update()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/kamiba/python_big_game.git
git@gitee.com:kamiba/python_big_game.git
kamiba
python_big_game
python_big_game
master

搜索帮助