-1
我的代碼存在問題,即時嘗試繪製六角形多邊形,但第n個顯示出來。當我嘗試使用eclipse或其他pygame.draw函數它沒問題,問題是多邊形。這是我的代碼。我覺得整個程序工作正常,問題就在這裏:Hexagon不顯示
hexagon = Hexagon.hexagon_generator(40,self.rect.x,self.rect.y)
pygame.draw.polygon(self.image,(0,225,0),list(hexagon),0)
整個程序:
import pygame
import random
import Hexagon
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Player(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.image = pygame.Surface([100,100])
self.rect = self.image.get_rect()
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.rect.x = x
self.rect.y = y
hexagon = Hexagon.hexagon_generator(40,self.rect.x,self.rect.y)
pygame.draw.polygon(self.image,(0,225,0),list(hexagon),0)
self.velocity_y = 0
self.velocity_x = 0
def move(self, x, y):
self.velocity_x += x
self.velocity_y += y
def update(self):
self.rect.x += self.velocity_x
self.rect.y += self.velocity_y
if self.rect.x >785:
self.rect.x =785
elif self.rect.x <0:
self.rect.x =0
elif self.rect.y > 585:
self.rect.y = 585
elif self.rect.y < 0:
self.rect.y = 0
elif self.rect.x<0 and self.rect.y < 0:
self.rect.x = 0
self.rect.y = 0
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])
all_sprites_list = pygame.sprite.Group()
player = Player(200,200)
all_sprites_list.add(player)
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player.move(0,5)
if event.key == pygame.K_UP:
player.move(0, -5)
if event.key == pygame.K_LEFT:
player.move(-5, 0)
if event.key == pygame.K_RIGHT:
player.move(5, 0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
player.move(0, -5)
if event.key == pygame.K_UP:
player.move(0, 5)
if event.key == pygame.K_LEFT:
player.move(5, 0)
if event.key == pygame.K_RIGHT:
player.move(-5, 0)
screen.fill(WHITE)
all_sprites_list.update()
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
有一個六邊形模塊:
import math
def hexagon_generator(edge_length, x,y):
for angle in range(0, 360, 60):
x += math.cos(math.radians(angle)) * edge_length
y += math.sin(math.radians(angle)) * edge_length
yield x, y
我只是固定的格式,但你還是應該儘量減少代碼轉換爲[最小,完整且可驗證的示例](https://stackoverflow.com/help/mcve)。這兩個模塊也可以加入。 – skrx