由于我比较想做个游戏出来,而且我也喜欢波兰球,所以做了一个波兰球游戏:
index.py
import pygame
import sys
import json
from player import Player
WIDTH = 800
HEIGHT = 600
BG = (0, 221, 225)
FPS=60
class Index:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.screenrect = self.screen.get_rect()
pygame.display.set_caption("PolandBall Attack Beta-1.0")
self.map = self.map_open("index_map")
self.run_game()
def run_game(self):
self.center_x, self.center_y = 0, 0
self.player = Player("RUSSIA", self)
self.fpsclock=pygame.time.Clock()
while True:
self.screen.fill(BG)
self.check_events()
self.update()
self.draw()
pygame.display.flip()
self.fpsclock.tick(FPS)
def check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
def quit(self):
pygame.quit()
sys.exit()
def update(self):
self.player.update()
# 更新中心点的位置,可以根据具体情况调整
self.center_x = self.player.rect.x - WIDTH // 2
self.center_y = self.player.rect.y - HEIGHT // 2
def draw(self):
self.draw_map()
self.player.draw()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.player.move(-5, 0)
if keys[pygame.K_RIGHT]:
self.player.move(5, 0)
if keys[pygame.K_UP]:
self.player.jump()
def draw_map(self):
for item in self.map:
self.draw_in_center_map(item, (0, 0, 0))
def draw_in_center_map(self, rect, color):
rect = rect.copy()
rect.x -= self.center_x
rect.y -= self.center_y
pygame.draw.rect(self.screen, color, rect)
def map_open(self, mapname):
with open(f"maps/{mapname}.map") as file:
mapo = json.load(file)
maps = []
for item in mapo:
maps.append(pygame.Rect(item[0], item[1], item[2], item[3]))
return maps
if __name__ == "__main__":
Index()
player.py
import pygame
class Player:
def __init__(self, country, arg):
self.arg = arg
self.img = pygame.image.load(f"countries/{country}.png")
self.rect = self.img.get_rect()
self.rect.x = 400
self.rect.y = -10000
self.downspeed=0
def draw(self):
# 计算实际绘制位置
draw_x = self.rect.x - self.arg.center_x
draw_y = self.rect.y - self.arg.center_y
self.arg.screen.blit(self.img, (draw_x, draw_y))
def is_collide(self):
for item in self.arg.map:
if self.rect.colliderect(item):
return True
return False
def move(self, xadd=0, yadd=0):
self.rect.x += xadd
self.rect.y += yadd
if self.is_collide():
self.rect.x -= xadd
self.rect.y -= yadd
def down(self):
self.rect.y+=self.downspeed
self.nowy=self.rect.y
if self.is_collide():
self.downspeed=-1
else:
self.downspeed+=1
def update(self):
self.down()
def jump(self):
if self.is_collide():
self.downspeed=-15
和scratch差不多的程序,有兴趣的可以收藏,用作跑酷游戏。
附文件夹(zipeed)
忘记说了,角色他是从高空掉下来的,要等一会儿。