[英]PyGame not drawing rectangle
pygame不起作用
我是 oop 編程的新手。 第一個)main.py 第二個)setting.py
from setting import *
import pygame
class Game:
def __init__(self):
pass
def game(self):
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
running = True
x=0
y=0
for row in MAP:
print(row)
for pos in row:
print(pos)
if pos == "x":
pygame.draw.rect(screen, [0, 0, 255], [x, y, 20, 20], 1)
x+=20
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(COLOR)
pygame.display.flip()
pygame.quit()
quit()
game = Game()
game.game()
二)setting.py
FPS = 60
WIDTH = 800
HEIGHT = 600
COLOR = [255,255,255]
TITLE = 'test'
MAP = [['x', 'x', 'x','x','x', 'x', 'x','x','x', 'x', 'x','x']
,['x', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'x']
,['x', ' ', ' ', 'P', ' ', ' ', ' ', ' ', ' ', ' ', 'x']
,['x', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'x']
,['x', 'x', 'x','x','x', 'x', 'x','x','x', 'x', 'x','x']
]
您需要在每一幀中重新繪制場景。 典型的 PyGame 應用循環必須:
pygame.time.Clock.tick
限制每秒幀數以限制 CPU 使用率pygame.event.pump()
或pygame.event.get()
來處理事件。blit
所有對象)pygame.display.update()
或pygame.display.flip()
更新顯示from setting import *
import pygame
class Game:
def __init__(self):
pass
def game(self):
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
running = True
while running:
# limit the frames per second
clock.tick(FPS)
# handle the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# clear the display
screen.fill(COLOR)
# draw all objects in the scene
for y, row in enumerate(MAP):
for x, pos in enumerate(row):
if pos == "x":
pygame.draw.rect(screen, [0, 0, 255], [x*20, y*20, 20, 20], 1)
# update the display
pygame.display.flip()
pygame.quit()
quit()
game = Game()
game.game()
map的定義可以簡化:
MAP = [
'xxxxxxxxxxxx',
'x x',
'x p x',
'x x',
'xxxxxxxxxxxx'
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.