Python初学者求助:如何将敌舰随机放置在游戏窗口右半区域
解决方法
先梳理你代码里的几个问题,再给出修正后的实现:
- 缺少
random模块导入,得先导入它 - 类实例化语法错误:
Enemy Ships()应该写成Enemy_Ships() - 调用类方法时要用实例对象调用,不是直接用类名调用
- 你定义的
self.x字典没用到,而且现在需要给每艘飞船单独生成右半区域的随机x坐标,而不是所有飞船共用同一个xmax
修正后的完整代码:
import pygame import random # 导入random模块 win_w = int(input("Enter the number of pixels corresponding to the width of the game window: ")) win_h = int(input("Enter the number of pixels corresponding to the height of the game window: ")) win = pygame.display.set_mode((win_w, win_h)) centre_of_win = win_w * 0.5 ships = ['ship1.png', 'ship2.png', 'ship3.png'] class Enemy_Ships: def __init__(self): # 给每艘飞船生成右半区域的随机x坐标,存入字典 self.x = {} for ship in ships: # 减去飞船宽度(50)避免超出窗口右侧 self.x[ship] = random.uniform(centre_of_win, win_w - 50) self.color = (0, 100, 100) def drawing_enemy(self, ships): for element in ships: # 随机生成y坐标,减去飞船高度(25)避免超出窗口底部 y_pos = random.randint(0, win_h - 25) rect = pygame.Rect(self.x[element], y_pos, 50, 25) pygame.draw.rect(win, self.color, rect, 1, win_w) # 正确实例化类 enemy = Enemy_Ships() # 用实例对象调用方法 enemy.drawing_enemy(ships) pygame.display.update()
关键说明
- 导入
random模块才能生成随机位置 - 每艘飞船单独生成右半区域的x坐标,确保位置不重复
- 计算坐标时减去飞船尺寸,避免绘制出窗口范围
- 修正了类实例化和方法调用的语法错误
内容的提问来源于stack exchange,提问作者NewbieInProgramming
相关产品推荐
相关产品推荐

