- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的代码中,我的 Sprite 可以在 x 轴上左右移动。但是,它可以从屏幕上消失。我想防止它超出屏幕。我不知道该怎么做,我试过写:
if event.key == pygame.K_LEFT and player.rect.x > 0:
#player moves left
但它没有成功。播放器 Sprite 刚从屏幕上消失,我无法让它回来。我愿意接受所有建议。提前致谢!我将代码分成三个不同的文件 -->
main.py :
import pygame
import os
import sys
import time
from pygame import mixer
from Sprite1 import *
from settings import *
'''
Setup
'''
pygame.init()
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player(all_sprites)
player.rect.x = 100
player.rect.y = 500
enemy_list = pygame.sprite.Group() # create enemy group
enemy = Enemy(enemy_list)# spawn enemy
enemy.rect.x = 400
enemy.rect.y = 470
showStartScreen(surface)
x = 0
'''
Main loop
'''
main = True
while main == True:
background = pygame.image.load(os.path.join('images', 'Bg.png')).convert()
font = pygame.font.Font('freesansbold.ttf', 32)
text = font.render('Health:', True, BLACK, surface)
textRect = text.get_rect()
textRect.center = (60, 30)
rel_x = x % background.get_rect().width
surface.blit(background, (rel_x - background.get_rect().width, 0))
if rel_x < width:
surface.blit(background, (rel_x, 0))
if player.rect.x >= 560:
x -= 10
elif player.rect.x <= 400:
x += 10
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
main = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.control(-steps,0)
if event.key == pygame.K_RIGHT:
player.control(steps,0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.control(steps,0)
if event.key == pygame.K_RIGHT:
player.control(-steps,0)
keys = pygame.key.get_pressed()
if not(isJump):
if keys[pygame.K_UP]:
isJump = True
else:
if jumpCount >= -10:
player.rect.y -= (jumpCount * abs(jumpCount)) * 1
jumpCount -= 2
else:
jumpCount = 10
isJump = False
if player.rect.y > width:
go_screen(surface)
surface.blit(text, textRect)
# dt = time since last tick in milliseconds.
dt = clock.tick(60) / 1000
all_sprites.update(dt, enemy_list)
player.update(dt, enemy_list)
enemy_list.update(dt, all_sprites)
all_sprites.draw(surface) #refresh player position
enemy_list.draw(surface)
for e in enemy_list:
e.move()
pygame.display.flip()
设置.py :
import pygame
isJump = False
jumpCount = 10
width = 960
height = 720
FONT_NAME = 'arial'
fps = 40 # frame rate
pygame.display.set_caption('B.S.G.')
surface = pygame.display.set_mode((width, height))
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_GRAV = 0.8
PLAYER_JUMP = 20
PLAYER_LAYER = 2
PLATFORM_LAYER = 1
BLACK = (0, 0, 0)
steps = 10 # how fast to move
Sprite 1 :
import pygame
import sys
import os
import time
from pygame import mixer
from pygame.locals import *
from settings import *
vec = pygame.math.Vector2
clock = pygame.time.Clock()
def showStartScreen(surface):
show = True
while (show == True):
background = pygame.image.load(os.path.join('images', 'Starting_scr.png'))
surface.blit(background, (0,0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
show = False
def go_screen(surface):
show = True
while (show == True):
background = pygame.image.load(os.path.join('images', 'GO_screen.png'))
surface.blit(background, (0,0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.quit()
sys.exit()
class Player(pygame.sprite.Sprite):
def __init__(self, all_sprites):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.frame = 0
self.health = 100
self.jumping = False
self.images = []
self.imagesleft = []
self.imagesright = []
self.imagesdownl = []
self.imagesdownr = []
self.direction = "right"
self.alpha = (0,0,0)
self.ani = 4 # animation cycles
self.all_sprites = all_sprites
self.add(self.all_sprites)
self.fire_timer = .1
self.bullet_timer = .1
self.pos = vec(40, height - 100)
self.vel = vec(0, 0)
self.counter = 0
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img = pygame.transform.rotate(img, -90)
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesdownl.append(img)
self.image = self.imagesdownl[0]
self.rect = self.image.get_rect()
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img = pygame.transform.flip(img, False, True)
img = pygame.transform.rotate(img, -90)
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesdownr.append(img)
self.image = self.imagesdownr[0]
self.rect = self.image.get_rect()
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img = pygame.transform.flip(img, True, False)
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesleft.append(img)
self.image = self.imagesleft[0]
self.rect = self.image.get_rect()
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesright.append(img)
self.image = self.imagesright[0]
self.rect = self.image.get_rect()
def control(self,x,y):
'''
control player movement
'''
self.movex += x
self.movey -= y
def update(self, dt, enemy_list):
'''
Update sprite position
'''
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# moving left
if self.movex < 0:
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesleft[self.frame//self.ani]
self.direction = "left"
# moving right
if self.movex > 0:
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesright[self.frame//self.ani]
self.direction = "right"
enemy_hit_list = pygame.sprite.spritecollide(self, enemy_list, False)
for enemy in enemy_hit_list:
self.health -= 10
if self.direction == "left":
self.rect.x += 100
else:
self.rect.x -= 100
print(self.health)
if self.health <= 0:
distance = 20
speed = 10
if self.counter >= distance and self.counter <= distance*2:
self.rect.y -= speed
self.counter += 1
if self.rect.y < 291:
self.movey = 10
if self.direction == "left":
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesdownr[self.frame//self.ani]
if self.direction == "right":
self.frame += 1
if self.frame > 3*self.ani:
self.frame = 0
self.image = self.imagesdownl[self.frame//self.ani]
if self.rect.y > height:
self.kill()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
self.bullet_timer -= dt # Subtract the time since the last tick.
if keys[pygame.K_x]:
self.fire_timer -= dt
if self.bullet_timer <= 0:
self.bullet_timer = 100 # Bullet ready.
if keys: # Left mouse button.
# Create a new bullet instance and add it to the groups.
if self.direction == "right":
Bullet([self.rect.x + self.image.get_width(), self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
else:
Bullet([self.rect.x, self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
self.bullet_timer = .5 # Reset the timer.
if self.fire_timer <= 0:
self.fire_timer = 100
if keys:
if self.direction == "right":
Fire([self.rect.x + 170, self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
else:
Fire([self.rect.x - 90, self.rect.y + self.image.get_height()/2], self.direction, self.all_sprites)
self.fire_timer = .1
class Enemy(pygame.sprite.Sprite):
'''
Spawn an enemy
'''
def __init__(self, enemy_list):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.health = 50
self.frame = 0
self.alpha = (0,0,0)
self.ani = 2 # animation cycles
self.enemy_list = enemy_list
self.add(self.enemy_list)
self.counter = 0 # counter variable
self.imagesleft = []
self.imagesright = []
for i in range(1,17):
img = pygame.image.load(os.path.join('images','Bot' + str(i) + '.png')).convert()
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesleft.append(img)
self.image = self.imagesleft[0]
self.rect = self.image.get_rect()
for i in range(1,17):
img = pygame.image.load(os.path.join('images','Bot' + str(i) + '.png')).convert()
img = pygame.transform.flip(img, True, False)
img.convert_alpha()
img.set_colorkey(self.alpha)
self.imagesright.append(img)
self.image = self.imagesright[0]
self.rect = self.image.get_rect()
def move(self):
'''
enemy movement
'''
distance = 30
speed = 10
if self.counter >= 0 and self.counter <= distance:
self.rect.x += speed
self.frame += 1
if self.frame > 15*self.ani:
self.frame = 0
self.image = self.imagesright[self.frame//self.ani]
elif self.counter >= distance and self.counter <= distance*2:
self.rect.x -= speed
self.frame += 1
if self.frame > 15*self.ani:
self.frame = 0
self.image = self.imagesleft[self.frame//self.ani]
else:
self.counter = 0
self.counter += 1
def update(self, dt, all_sprites):
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
bullet_list = pygame.sprite.spritecollide(self, all_sprites, True)
for bullets in bullet_list:
self.health -= 10
print(self.health)
if self.health <= 0:
img = pygame.image.load(os.path.join('images','E_dead.png')).convert()
img.convert_alpha()
img.set_colorkey(self.alpha)
self.image = img
distance = 5
speed = 10
if self.counter >= 0 and self.counter <= distance:
self.rect.x += speed
elif self.counter >= distance and self.counter <= distance*2:
self.rect.x -= speed
else:
self.counter = 0
self.counter += 1
self.movey = -20
if self.rect.y < -50:
self.kill()
class Bullet(pygame.sprite.Sprite):
IMAGE = None
FLIPPED_IMAGE = None
def __init__(self, pos, direction, *sprite_groups):
super().__init__(*sprite_groups)
# cache images
if not Bullet.IMAGE:
Bullet.IMAGE = pygame.image.load(os.path.join('images','fireball.png'))
Bullet.FLIPPED_IMAGE = pygame.transform.flip(Bullet.IMAGE, True, False)
if direction == "right":
self.vel = pygame.math.Vector2(750, 0)
self.image = Bullet.IMAGE
else:
self.vel = pygame.math.Vector2(-750, 0)
self.image = Bullet.FLIPPED_IMAGE
self.pos = pygame.math.Vector2(pos)
self.rect = self.image.get_rect(center=pos)
def update(self, dt, enemy_list):
# Add the velocity to the position vector to move the sprite
self.pos += self.vel * dt
self.rect.center = self.pos # Update the rect pos.
if not pygame.display.get_surface().get_rect().colliderect(self.rect):
self.kill()
class Fire(pygame.sprite.Sprite):
IMAGE = None
FLIPPED_IMAGE = None
def __init__(self, pos, direction, *sprite_groups):
super().__init__(*sprite_groups)
# cache images
if not Fire.IMAGE:
Fire.IMAGE = pygame.image.load(os.path.join('images','fire_drag.png'))
Fire.FLIPPED_IMAGE = pygame.transform.flip(Fire.IMAGE, True, False)
if direction == "right":
self.image = Fire.IMAGE
self.vel = pygame.math.Vector2(0, 0)
else:
self.image = Fire.FLIPPED_IMAGE
self.vel = pygame.math.Vector2(0, 0)
self.pos = pygame.math.Vector2(pos)
self.rect = self.image.get_rect(center=pos)
def update(self, dt, enemy_list):
self.too = True
self.pos += self.vel * dt
self.rect.center = self.pos # Update the rect pos.
if self.too == True:
self.kill()
再次感谢!
最佳答案
Player.control
只是设置了播放器的移动方向,但是不会移动播放器,所以省略plyer.control()
的调用完全没用.您必须在方法 update
中阻止和限制玩家的移动:
class Player(pygame.sprite.Sprite):
# [...]
def update(self, dt, enemy_list):
self.rect.x += self.movex
self.rect.y += self.movey
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > width:
self.rect.right = width
if self.rect.top < 0:
self.rect.top = 0
elif self.rect.bottom > height:
self.rect.bottom = height
# [...]
关于python - 在 pygame 中设置 Sprite 旅行限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63090830/
Surface.blit在 1.8 中有一个新参数:混合。定义了以下值: BLEND_ADD BLEND_SUB BLEND_MULT BLEND_MIN BLEND_MAX BLEND_RGBA_A
import sys import pygame import pygame.locals as pgl class Test: def __init__(self): pyg
我对 PyGame 比较陌生。我正在尝试制作一个简单的程序来显示表示鼠标在屏幕上的位置的字符串。 import pygame, sys from pygame.locals import * pyga
我有总是在后台运行的音乐和一些在触发时会播放声音的事件。音乐效果很好。 pygame.mixer.music.load(os.path.join(SOUND_FOLDER, 'WateryGrave.
我有这些代码 FONT = pygame.font.Font("font/calibri.ttf", 50) FONT.size = 25 但是编译器说 AttributeError: 'pygame
有我正在导入的图像: look_1 = pygame.image.load('data\\png\\look1.png').convert_alpha() 我试图减少它的大小是这样的: pygame.
我正在为我的 pygame 制作一个帮助屏幕,每当我运行它时,我都会收到此错误消息: > self.surface.blit(self.helpscreen) TypeError: argument
在 pyGame 中应用程序,我想渲染 SVG 中描述的无分辨率 GUI 小部件。 我怎样才能做到这一点? (我喜欢 OCEMP GUI 工具包,但它的渲染似乎依赖于位图) 最佳答案 这是一个完整的例
有没有办法将多首歌曲加载到 Pygame 中?我不是在谈论这样的音效; crash_sound = pygame.mixer.Sound("crash.ogg") #and pygame.mixer.
我还有一个问题。当我尝试运行我的代码时,pygame 启动然后立即停止。 这是我的代码: import pygame import os import time import random pygam
我正在使用 pymunk 和 pygame 开发一个项目。我正在使用 PivotJoint 约束将我的 body 连接在一起。如果可能的话,我想让关节不可见 - 有什么办法可以做到这一点吗?现在关节在
我使用 fedora 20、Python 2.7 和 virtualenv 1.10.1。我想在 virtualenv 中安装 pygame,我得到了 You are installing a pot
尝试将文本添加到矩形中并使用箭头键在屏幕上移动矩形。我想让文字不会超出边缘。到目前为止,我已经在没有将其放入 Rect 中的情况下工作了,但我想让 Rect 函数工作。现在文本只是反弹回来,我不知道要
我是第一次玩 pygame(总的来说我是 python 的新手),想知道是否有人可以帮助我... 我正在制作一款小型射击游戏,希望能够为坏人创建一个类。我的想法是类应该继承自 pygame.Surfa
我在 Windows 10 机器上运行了 python 3.9.1。我通过 pip 在我的机器上安装了 pygame 2.0.1 (python -m pip install https://gith
错误: File "/home/alien/cncell/core/animator.py", line 413, in create_animation_from_data pygame
这是代码。 5000 个弹跳旋转的红色方块。 (16x16 png) 在 pygame 版本上,我获得 30 fps,但使用 pyglet 获得 10 fps。对于这种事情,OpenGl 不应该更快吗
我以为 pygame.font.Font 是用来加载 .ttf 字体的,如果没有 .ttf 文件在同一个目录下就无法加载字体,但我看过一个视频,有人在没有 .ttf 文件的情况下加载字体。 ttf 字
我正在尝试使用 Travis CI 设置一个项目。项目也使用 pygame。我曾多次尝试设置它 - 但它似乎失败了。 我得到的最接近的是以下内容: .travis.yml : language: py
这个问题已经有答案了: Python error "ImportError: No module named" (38 个回答) 已关闭 3 年前。 我正在使用 Mac 并输入 pip install
我是一名优秀的程序员,十分优秀!