python - 如何让我的 pygame tron 游戏吸引玩家?
问题描述
我正在尝试制作的 tron 游戏不会运行实际角色。我已经为玩家一和玩家二创建了一个类,并且在 while 循环中我放置了一个绘图命令,但它仍然没有运行游戏。任何提示或解决方案?很抱歉代码中缺少注释。
import pygame
pygame.init()
black = 0,0,0 #Create black for background
P1_Color = 0,0,225 #Create blue for player 1
P2_Color = 255,0,0 #Create red for player 2
class Player:
def __init__(self, x, y, direction, color, position):
self.x = x #X coord
self.y = y #Y coord
self.position = (x,y)
self.direction = direction #direction
self.color = color #color
self.rect = pygame.Rect(100, self.y - 1, 2, 2) #player rect object
def draw(self):
self.rect = pygame.Rect(100, self.y - 1, 2, 2) # redefines rect
pygame.draw.rect(screen, self.color, self.rect, 0) # draws player onto screen
def move(self):
self.x += self.direction[0] * 2
self.y += self.direction[1] * 2
screen = pygame.display.set_mode((1000, 750)) # creates window
pygame.display.set_caption("Tron") # sets window title
clock = pygame.time.Clock()
p1 = Player(50, 0, (2, 0), P1_Color, (500,0)) # creates p1
p2 = Player(50, 50, (-2, 0), P2_Color, (0,500)) #create p2
done = False
while not done:
for event in pygame.event.get(): # gets all event in last tick
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
# === Player 1 === #
if event.key == pygame.K_w:
p1.direction = (0, -2)
elif event.key == pygame.K_s:
p1.direction = (0, 2)
elif event.key == pygame.K_a:
p1.direction = (-2, 0)
elif event.key == pygame.K_d:
p1.direction = (2, 0)
# === Player 2 === #
if event.key == pygame.K_UP:
p2.direction = (0, -2)
elif event.key == pygame.K_DOWN:
p2.direction = (0, 2)
elif event.key == pygame.K_LEFT:
p2.direction = (-2, 0)
elif event.key == pygame.K_RIGHT:
p2.direction = (2, 0)
screen.fill(black)
p1.draw()
p1.move()
p2.draw()
p2.move()
pygame.quit()
解决方案
您必须使用pygame.display.update()
或更新显示pygame.display.flip()
:
done = False
while not done:
# [...]
screen.fill(black)
p1.draw()
p1.move()
p2.draw()
p2.move()
pygame.display.update()
推荐阅读
- rest - 使用 Drupal 8 Rest API 上传文件时 Postman 出现边界错误
- jupyter-notebook - MethodError: 没有方法匹配 /(::Int64, ::typeof(r)) [Julia]
- elasticsearch - Elasticsearch:在大索引中添加新字段
- java - Spring JdbcTemplate 将查询结果映射到自定义类
- python - Python中的可变变量和内存管理
- java - 如何检查 *.war 文件的导入?
- python - 将 Stackoverflow 中发布的数据导入 Python 工作环境的最佳实践
- javascript - 延迟while循环并刷新Div的内容
- c++ - 如何使指针显示对象的字符串变量?
- javascript - JavaScript 基于存储日期的夏令时