[英]How make that my left click of the mouse draw a cercle in the board tic tac toe game with tkinter, python
[英]Failed to make my player rotate as my mouse on my Python game
我已经阅读了所有类似的主题,但是找不到问题。 我编写了一个python游戏,我希望玩家通过方向箭头移动并通过鼠标旋转。
当我编写有关旋转的代码时,我退出错误:
Player
对象没有属性position
我尝试了许多在互联网上找到的不同解决方案,但是没有任何变化。
class Player(pygame.sprite.Sprite):
#change_x = 0
#change_y = 0
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load("player1.gif").convert()
#self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.change_x = 0
self.change_y = 0
self.walls = None
def changespeed(self, x, y):
self.change_x += x
self.change_y += y
def move(self, walls):
self.rect.x += self.change_x
block_hit_list = pygame.sprite.spritecollide(self, walls, False)
for block in block_hit_list:
if self.change_x > 0:
self.rect.right = block.rect.left
else:
self.rect.left = block.rect.right
self.rect.y += self.change_y
block_hit_list = pygame.sprite.spritecollide(self, walls, False)
for block in block_hit_list:
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
def rotate(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
self.image = pygame.transform.rotate(self.image, int(angle))
self.rect = self.image.get_rect(center=self.position)
这是我添加旋转功能后的代码。 哪里出了毛病,我怎么称呼主循环为旋转呢?
图像( pygame.Surface
)可以通过pygame.transform.rotate
旋转。
如果逐步完成图像处理,则图像会失真并迅速增加。 请参阅“ 如何使用Pygame如何围绕图像中心旋转图像”的答案?
为了解决这个问题,您必须保留原始图像,并在Player
类的构造函数中分配.image
属性的副本:
self.image_source = pygame.image.load("player1.gif").convert()
self.image = self.image_source.copy()
旋转原始图像和更新属性.image
的方法rotate
:
self.image = pygame.transform.rotate(self.image_source, int(angle))
self.rect = self.image.get_rect(center=self.rect.center)
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image_source = pygame.image.load("player1.gif").convert()
self.image = self.image_source.copy()
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.change_x = 0
self.change_y = 0
self.walls = None
def rotate(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
self.image = pygame.transform.rotate(self.image_source, int(angle))
self.rect = self.image.get_rect(center=self.rect.center)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.